Valid Square - Problem

Imagine you're a quality inspector at a precision manufacturing company that creates square components. You're given the coordinates of four corner points in 2D space, but they're not in any particular order. Your job is to determine whether these points actually form a valid square.

A valid square must satisfy these geometric properties:

  • Four equal sides with positive length
  • Four equal angles (90-degree angles)
  • All corners are distinct points

Input: Four points p1, p2, p3, p4 where each point is represented as [x, y] coordinates

Output: Return true if the four points construct a perfect square, false otherwise

Challenge: The points are given in random order, so you need to figure out which points are adjacent and which are diagonally opposite!

Input & Output

example_1.py — Valid Square
$ Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: true
💡 Note: These four points form a unit square. All sides have length 1, and both diagonals have length √2. The distance pattern [1,1,1,1,2,2] confirms it's a square.
example_2.py — Invalid Rectangle
$ Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]
Output: false
💡 Note: These points form a rectangle, not a square. The sides have different lengths, so it fails the equal sides requirement.
example_3.py — Duplicate Points
$ Input: p1 = [1,0], p2 = [1,0], p3 = [0,1], p4 = [0,0]
Output: false
💡 Note: Two points are identical, which means we don't have 4 distinct corners. A valid square requires 4 unique points.

Visualization

Tap to expand
Distance Analysis:✓ 4 sides = 150 units✓ 2 diagonals = 212 units✓ 212² = 2 × 150²✓ Valid Square!ABCD
Understanding the Visualization
1
Measure All Distances
Calculate the 6 distances between every pair of points
2
Sort and Group
Sort distances to identify patterns - squares have 4 equal short distances and 2 equal long distances
3
Apply Pythagorean Check
Verify that diagonal length equals √2 times the side length
Key Takeaway
🎯 Key Insight: A square has exactly 4 equal sides and 2 equal diagonals, with diagonal² = 2 × side²

Time & Space Complexity

Time Complexity
⏱️
O(1)

Always calculate exactly 6 distances regardless of input

n
2n
Linear Growth
Space Complexity
O(1)

Only store the 6 distances and a few variables

n
2n
Linear Space

Constraints

  • p1.length == p2.length == p3.length == p4.length == 2
  • -104 <= xi, yi <= 104
  • All coordinates are integers
  • Edge case: Points may be given in any order
Asked in
Google 28 Amazon 22 Microsoft 18 Apple 12
26.8K Views
Medium Frequency
~15 min Avg. Time
892 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