Skip to problem
←

Valid Square

Medium 0 attempts

Given four points p1, p2, p3, and p4, each written as [x, y], return whether they are the four vertices of a square.

A square has four equal sides of positive length and four right angles. It may be rotated; its sides do not have to be parallel to the coordinate axes.

The points are provided in arbitrary order, not necessarily in order around the boundary. Repeated points, collinear points, non-square rectangles, and rhombuses without right angles are invalid. Return a boolean.

Function contract

Implement validSquare(p1, p2, p3, p4).

Output: Return true if the four points form a square with positive side length; otherwise return false.

Example 1

Input
p1 = [0,0]
p2 = [1,1]
p3 = [1,0]
p4 = [0,1]
Output
true

Example 2

Input
p1 = [0,0]
p2 = [0,0]
p3 = [1,1]
p4 = [1,0]
Output
false
Visual Aid
A square can be rotated
(0, 1)(1, 0)(0, −1)(−1, 0)

All four sides have squared length 2, and both diagonals have squared length 4. The input points may appear in any order.

Constraints
  • Coordinates are integers in range [-10^4, 10^4]
  • Each point is an array [x, y] of exactly two coordinates.
Topics

Distance Check

Compute all six pairwise squared distances and sort them. A square has four equal, nonzero side distances and two equal diagonal distances, each exactly twice a side distance. These checks are independent of input order and reject repeated points.

Squared distances avoid square roots and floating-point tolerance. Under the coordinate bounds, every squared distance is at most 800000000, which is exactly representable as a JavaScript integer.

javascript
function validSquare(p1, p2, p3, p4) {
  function dist(a, b) { return (a[0]-b[0])**2 + (a[1]-b[1])**2; }
  const dists = [dist(p1,p2),dist(p1,p3),dist(p1,p4),dist(p2,p3),dist(p2,p4),dist(p3,p4)].sort((a,b)=>a-b);
  return dists[0] > 0 && dists[0]===dists[1] && dists[1]===dists[2] && dists[2]===dists[3] && dists[4]===dists[5] && dists[4]===2*dists[0];
}

Time: O(1) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript