Valid Square
Medium · Math · Math · Geometry
Problem
You are given four points p1, p2, p3 and p4 in the plane, each as [x, y], listed in no particular order.
Return true if the four points are the corners of a square: four sides of equal, positive length and four right angles. The square may be tilted; it does not have to line up with the axes.
Examples
Input: p1 = [1,0], p2 = [0,1], p3 = [-1,0], p4 = [0,-1] Output: true
These points form a square turned 45 degrees: every side has squared length 2 and both diagonals 4.
Input: p1 = [0,0], p2 = [2,0], p3 = [2,1], p4 = [0,1] Output: false
A 2 x 1 rectangle: right angles, but the sides differ.
Input: p1 = [3,3], p2 = [3,3], p3 = [3,3], p4 = [3,3] Output: false
All four points coincide, so the side length is zero.
Constraints
- len(p1) == len(p2) == len(p3) == len(p4) == 2
- -10^4 <= xi, yi <= 10^4
Approaches
- Baseline: try every corner order — time O(4! · 4), space O(1)
Follow-up
With integer coordinates, "exactly two distinct distances, none zero" is also enough, because no three integer points form an equilateral triangle; with real coordinates a 60-degree rhombus would pass that test. The sorted check with d[4] == 2 · d[0] holds for any coordinates.
Related problems
Start free on Cariara · Coding problems · System design studio