Skip to content
Problem 593 · LeetCode 593(opens in a new tab)

Valid Square

MediumGeometry

You get four points on a plane, p1, p2, p3 and p4, each written as [x, y]. They come in no particular order.

Return true if the four points are the corners of a square: four sides of the same, non-zero length and four right angles. The square may be tilted. Otherwise return false.

Example 1

Input:  p1 = [3, 3], p2 = [1, 1], p3 = [1, 3], p4 = [3, 1]
Output: true
Why:    a 2 by 2 square, listed out of order
2 more examples and the constraints

Example 2

Input:  p1 = [0, 0], p2 = [2, 1], p3 = [1, 3], p4 = [-1, 2]
Output: true
Why:    a tilted square; every side is the root of 5

Example 3

Input:  p1 = [0, 0], p2 = [2, 1], p3 = [4, 0], p4 = [2, -1]
Output: false
Why:    four equal sides, but the diagonals are 4 and 2 long

Constraints

  • Each point has exactly two coordinates
  • −10,000 ≤ x, y ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try each corner orderO(1)
  2. Sort all six distancesO(1)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for one set of four pointsVerdict
Try each corner orderO(1)
Works; easy to get an order wrong
Sort all six distancesO(1)
Best; no order to guess

Both are constant time; work counts distance computations (18 against 6, plus a tiny sort).

Edge cases to test

  • All four points the same. Every distance is 0; the side > 0 check returns false.
  • Repeated points. [-1, 0], [3, -2], [-1, 0], [3, -2] walked in order has four equal sides and two equal (zero) diagonals; it must still be false.
  • A rhombus. Four equal sides with unequal diagonals, like Example 3, is not a square.
  • A rectangle. Equal diagonals but two side lengths, so the first four distances differ.
  • Tilted and large. [-10000, 0], [0, -10000], [10000, 0], [0, 10000] is a square; its diagonal squared is 400,000,000.

Common mistakes

  • Forgetting the non-zero check, so four copies of one point pass.
  • Assuming the points are given in order around the square.
  • Using real square roots and comparing floats, which can disagree by rounding.

How to talk through it

  1. 1Clarify. Can points repeat? Can the square be tilted? Are the points in any order?
  2. 2Give the first idea. Try the three orders around p1 and check sides and diagonals.
  3. 3Find what does not depend on order. The six pairwise distances: four sides, two diagonals.
  4. 4Code the sorted check. Squared distances, sort, then compare the first four and the last two.
  5. 5Test out loud. Run four equal points, a rhombus and a rectangle before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?