(Translated by https://www.hiragana.jp/)
Check if given four points form a square - GeeksforGeeks
Open In App

Check if given four points form a square

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given coordinates of four points in a plane, find if the four points form a square or not. 

Examples:

Input: p1 = { 20, 10 }, p2 = { 10, 20 }, p3 = { 20, 20 }, p4 = { 10, 10 }
Output: Yes
Explanation: 

Input: p1 = { 20, 20 }, p2 = { 10, 20 }, p3 = { 20, 20 }, p4 = { 10, 10 }
Output:  No

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 Rhombus also 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 !

C++
Java Python C# JavaScript

Output
Yes

Time Complexity: O(1), all operations are being carried out in O(1) constant time.
Auxiliary Space: O(1), no extra space required

Extended Problem: 


Article Tags :

Similar Reads