Short, Quick & Clean C++ Solution

• Mathematically the distance between two points can be derived from the Pythagoras theorem i.e. x^2 + y^2 = z^2 (more info here: https://www.mathsisfun.com/algebra/distance-2-points.html). Here we use an unordered map to store the distance between the two points as the key and the value is the frequency of it's occurrence. If it appears four times and the other two distances (diagonals) appear twice, then it is a valid square by definition.

``````int distanceSquared(vector<int>& x, vector<int>& y){
return (x[1]-y[1])*(x[1]-y[1]) + (x[0]-y[0])*(x[0]-y[0]);
}

bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
unordered_map<int, int> myMap;
myMap[distanceSquared(p1,p2)]++;
myMap[distanceSquared(p1,p3)]++;
myMap[distanceSquared(p1,p4)]++;
myMap[distanceSquared(p2,p3)]++;
myMap[distanceSquared(p2,p4)]++;
myMap[distanceSquared(p3,p4)]++;
for(auto it=myMap.begin(); it!=myMap.end(); ++it)
if(it->second==4 && myMap.size()==2) return true;
return false;
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.