Given the coordinates of four points in 2D space p1, p2, p3 and p4, return true if the four points construct a square.
The coordinate of a point pi is represented as [xi, yi]. The input is not given in any order.
A valid square has four equal sides with positive length and four equal angles (90-degree angles).
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: true
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,12]
Output: false
Input: p1 = [1,0], p2 = [-1,0], p3 = [0,1], p4 = [0,-1]
Output: true
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:
To solve this brute force, we calculate the distance between each pair of given points and then check the distribution of these distances.
We can simplify the check by sorting the points and then analyzing the ordered sequence of distances. The key observation is:
We can calculate squared distances from a fixed reference, then check fixed positions' conditions of distances.