Given an 2D array points[] which represents coordinates of four points in a plane. Find if the four points can form a square or not. Return true if they form a square else return false.
Examples:
Input: points[] = {{0, 0}, {0, 1}, {1, 0}, {1, 1}} Output: true Explanation: These points form a square which can be clearly seen in the below image.
To check for square, we need to check for following. a) All four sides formed by points are the same. b) The angle between any two sides is 90 degree. (This condition is required as Rhombusalso has same sides) c) Check both the diagonals have the same distance.
The idea is to pick any point and calculate its distance from the rest of the points. Let the picked point be 'p'. To form a square, the distance of two points must be the same from 'p', let this distance be d. The distance from one point must be different from that d and must be equal to √2 times d (or distance square should be equal to 2 * d2). Let this point with different distance be 'q'.
The above condition is not good enough as the point with a different distance can be on the other side. We also need to check that q is at the same distance from 2 other points and this distance is the same as d.
Here in the code below for the sake of simplicity we are calculating distance as (x1-x2)2 +(y1-y2)2. WE ARE NOT SQUARE ROOTING IT !
Output
true
Time Complexity: O(1), all operations are being carried out in O(1) constant time. Auxiliary Space: O(1), no extra space required