AlgoMaster Logo

Valid Square

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The problem of detecting whether four points can form a square boils down to ensuring that there are two unique distances: the side of the square and the diagonal (which is the hypotenuse of the two sides of a right angle triangle formed by two consecutive sides).

For four points to form a square:

  • The shortest distances (there should be 4 of them) are the sides of the square.
  • The longest distances (there should be 2 of them) are the diagonals.

To solve this brute force, we calculate the distance between each pair of given points and then check the distribution of these distances.

Code:

2. Sorting and Comparison

Intuition:

We can simplify the check by sorting the points and then analyzing the ordered sequence of distances. The key observation is:

  • If you sort points based on their x-coordinate (and secondarily upon y-coordinate if x's are equal), a square’s points will have inherent order allowing easy direct pairwise comparison.

We can calculate squared distances from a fixed reference, then check fixed positions' conditions of distances.

Code: