Valid Square - Problem

Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square.

The coordinate of a point p_i is represented as [x_i, y_i]. The input is not given in any order.

A valid square has four equal sides with positive length and four equal angles (90-degree angles).

Input & Output

Example 1 — Valid Square
$ Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: true
💡 Note: The four points form a unit square. All sides have length 1, and both diagonals have length √2.
Example 2 — Invalid Square
$ Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]
Output: false
💡 Note: The points do not form a square because the sides have different lengths.
Example 3 — Collinear Points
$ Input: p1 = [1,0], p2 = [2,0], p3 = [3,0], p4 = [4,0]
Output: false
💡 Note: All four points lie on the same line, so they cannot form a square.

Constraints

  • The coordinates of all four points are integers
  • -104 ≤ xi, yi ≤ 104
  • All four points are distinct

Visualization

Tap to expand
Valid Square Problem INPUT x y p1(0,0) p2(1,1) p3(1,0) p4(0,1) p1 = [0,0] p2 = [1,1] p3 = [1,0] p4 = [0,1] 4 points in 2D space (random order) ALGORITHM STEPS 1 Find Center Point Avg of all x, y coords C = (0.5, 0.5) 2 Calc Distances to Center Each point to center d1=d2=d3=d4=0.707 3 Check Equal Distances All 4 must be same All equal [OK] 4 Verify Side Lengths Check adjacent sides side = 1.0, diag = 1.414 4 equal sides [OK] FINAL RESULT center s=1 s=1 s=1 s=1 Output: true Valid Square Confirmed! [OK] 4 equal sides [OK] Equal diagonals [OK] Positive length Key Insight: The Center and Side Length approach uses geometry: a valid square has all 4 vertices equidistant from the center point. Calculate center as average of coordinates, then verify all distances are equal and positive. This approach avoids complex angle calculations. Time: O(1), Space: O(1) TutorialsPoint - Valid Square | Center and Side Length Check Approach
Asked in
Google 25 Microsoft 20 Apple 15 Facebook 12
32.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen