Valid Square Medium 0 attempts
LeetCode ↗

Valid Square

Medium MatrixBFSDFS LeetCode

You're given four points on a plane, listed in no particular order. Work out whether they're the corners of a genuine square — meaning all four sides are the same length and all four interior angles are right angles.

Input Format
Implement validSquare(p1, p2, p3, p4). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.

Sample Input and Output

Example 1 · Run Sample

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
Constraints
  • Coordinates are integers in range [-10^4, 10^4]
Test Cases (2)
Case 1
Args: [[0,0],[1,1],[1,0],[0,1]] Expected: true
Case 2
Args: [[0,0],[0,0],[1,1],[1,0]] Expected: false
Topics

Distance Check

A valid square has 4 equal sides and 2 equal diagonals.

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];
}

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

Saved in this browser only. Private to you.

JavaScript