Valid Square

Compute all 6 pairwise squared distances — a square has exactly 4 equal smaller and 2 equal larger, with the diagonal = side * sqrt(2).

Medium
Time O(1) Space O(1)
LeetCode
4 min read
geometry math

Problem#

Given 4 points, return true iff they form a square (any orientation, non-degenerate).

Examples#

  • (0,0), (1,1), (1,0), (0,1)true.
  • (0,0), (1,1), (1,0), (0,12)false.

Constraints#

  • Integer coordinates.

Approach#

Compute all 6 pairwise squared distances. A square has 4 equal “side” distances and 2 equal “diagonal” distances, with diagonal² = 2 * side². Also reject degenerate cases (zero side).

Solution#

Valid Square
class Solution {
public:
bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
auto d2 = [](vector<int>& a, vector<int>& b) {
long long dx = a[0] - b[0], dy = a[1] - b[1];
return dx * dx + dy * dy;
};
vector<long long> ds = {d2(p1,p2), d2(p1,p3), d2(p1,p4), d2(p2,p3), d2(p2,p4), d2(p3,p4)};
sort(ds.begin(), ds.end());
if (ds[0] == 0) return false;
return ds[0] == ds[1] && ds[1] == ds[2] && ds[2] == ds[3]
&& ds[4] == ds[5] && ds[4] == 2 * ds[0];
}
};

Editorial#

Using squared distances avoids floats. Sorting the 6 distances groups the 4 sides at the bottom and 2 diagonals at the top. The diagonal = 2 * side invariant rules out non-square rhombi/rectangles.

Complexity#

  • Time: O(1).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.