The Wayback Machine - https://web.archive.org/web/20240927195250/https://www.geeksforgeeks.org/check-given-four-points-form-square/
Open In App

How to check if given four points form a square

Last Updated : 25 Oct, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
22.42%
17.8K

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

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

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

 

Approach: 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. 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.

Below are the implementations of the above idea. 

C++




// A C++ program to check if four given points form a square or not.
#include <iostream>
using namespace std;
 
// Structure of a point in 2D space
struct Point {
    int x, y;
};
 
// A utility function to find square of distance
// from point 'p' to point 'q'
int distSq(Point p, Point q)
{
    return (p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y);
}
 
// This function returns true if (p1, p2, p3, p4) form a
// square, otherwise false
bool isSquare(Point p1, Point p2, Point p3, Point p4)
{
    int d2 = distSq(p1, p2); // from p1 to p2
    int d3 = distSq(p1, p3); // from p1 to p3
    int d4 = distSq(p1, p4); // from p1 to p4
 
    if (d2 == 0 || d3 == 0 || d4 == 0)   
        return false;
 
    // If lengths if (p1, p2) and (p1, p3) are same, then
    // following conditions must met to form a square.
    // 1) Square of length of (p1, p4) is same as twice
    // the square of (p1, p2)
    // 2) Square of length of (p2, p3) is same
    // as twice the square of (p2, p4)
 
    if (d2 == d3 && 2 * d2 == d4
        && 2 * distSq(p2, p4) == distSq(p2, p3)) {
        return true;
    }
 
    // The below two cases are similar to above case
    if (d3 == d4 && 2 * d3 == d2
        && 2 * distSq(p3, p2) == distSq(p3, p4)) {
        return true;
    }
    if (d2 == d4 && 2 * d2 == d3
        && 2 * distSq(p2, p3) == distSq(p2, p4)) {
        return true;
    }
 
    return false;
}
 
// Driver program to test above function
int main()
{
    Point p1 = { 20, 10 }, p2 = { 10, 20 },
          p3 = { 20, 20 }, p4 = { 10, 10 };
    isSquare(p1, p2, p3, p4) ? cout << "Yes" : cout << "No";
    return 0;
}


Java




// A Java program to check if four given points form a square or not.
 
class GFG
{
 
// Structure of a point in 2D space
static class Point
{
    int x, y;
 
        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
     
};
 
// A utility function to find square of distance
// from point 'p' to point 'q'
static int distSq(Point p, Point q)
{
    return (p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y);
}
 
// This function returns true if (p1, p2, p3, p4) form a
// square, otherwise false
static boolean isSquare(Point p1, Point p2, Point p3, Point p4)
{
    int d2 = distSq(p1, p2); // from p1 to p2
    int d3 = distSq(p1, p3); // from p1 to p3
    int d4 = distSq(p1, p4); // from p1 to p4
 
    if (d2 == 0 || d3 == 0 || d4 == 0)   
        return false;
 
    // If lengths if (p1, p2) and (p1, p3) are same, then
    // following conditions must met to form a square.
    // 1) Square of length of (p1, p4) is same as twice
    // the square of (p1, p2)
    // 2) Square of length of (p2, p3) is same
    // as twice the square of (p2, p4)
 
    if (d2 == d3 && 2 * d2 == d4
        && 2 * distSq(p2, p4) == distSq(p2, p3))
    {
        return true;
    }
 
    // The below two cases are similar to above case
    if (d3 == d4 && 2 * d3 == d2
        && 2 * distSq(p3, p2) == distSq(p3, p4))
    {
        return true;
    }
    if (d2 == d4 && 2 * d2 == d3
        && 2 * distSq(p2, p3) == distSq(p2, p4))
    {
        return true;
    }
 
    return false;
}
 
// Driver code
public static void main(String[] args)
{
    Point p1 = new Point(20, 10), p2 = new Point( 10, 20 ),
        p3 = new Point(20, 20 ), p4 = new Point( 10, 10 );
    System.out.println(isSquare(p1, p2, p3, p4)==true ? "Yes" : "No");
}
}
 
// This code is contributed by PrinciRaj1992


Python3




# A Python3 program to check if
# four given points form a square or not.
class Point:
     
    # Structure of a point in 2D space
    def __init__(self, x, y):
        self.x = x
        self.y = y
 
# A utility function to find square of
# distance from point 'p' to point 'q'
def distSq(p, q):
    return (p.x - q.x) * (p.x - q.x) +\
           (p.y - q.y) * (p.y - q.y)
 
# This function returns true if (p1, p2, p3, p4)
# form a square, otherwise false
def isSquare(p1, p2, p3, p4):
 
    d2 = distSq(p1, p2) # from p1 to p2
    d3 = distSq(p1, p3) # from p1 to p3
    d4 = distSq(p1, p4) # from p1 to p4
 
    if d2 == 0 or d3 == 0 or d4 == 0:   
        return False
 
    # If lengths if (p1, p2) and (p1, p3) are same, then
    # following conditions must be met to form a square.
    # 1) Square of length of (p1, p4) is same as twice
    # the square of (p1, p2)
    # 2) Square of length of (p2, p3) is same
    # as twice the square of (p2, p4)
 
    if d2 == d3 and 2 * d2 == d4 and \
                    2 * distSq(p2, p4) == distSq(p2, p3):
        return True
 
    # The below two cases are similar to above case
    if d3 == d4 and 2 * d3 == d2 and \
                    2 * distSq(p3, p2) == distSq(p3, p4):
        return True
 
    if d2 == d4 and 2 * d2 == d3 and \
                    2 * distSq(p2, p3) == distSq(p2, p4):
        return True
 
    return False
 
# Driver Code
if __name__=="__main__":
    p1 = Point(20, 10)
    p2 = Point(10, 20)
    p3 = Point(20, 20)
    p4 = Point(10, 10)
     
    if isSquare(p1, p2, p3, p4):
        print('Yes')
    else:
        print('No')
 
# This code is contributed by Mayank Chaudhary
# aka chaudhary_19


C#




// A C# program to check if four given points form a square or not.
using System;
 
class GFG
{
 
// Structure of a point in 2D space
class Point
{
    public int x, y;
 
    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
     
};
 
// A utility function to find square of distance
// from point 'p' to point 'q'
static int distSq(Point p, Point q)
{
    return (p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y);
}
 
// This function returns true if (p1, p2, p3, p4) form a
// square, otherwise false
static bool isSquare(Point p1, Point p2, Point p3, Point p4)
{
    int d2 = distSq(p1, p2); // from p1 to p2
    int d3 = distSq(p1, p3); // from p1 to p3
    int d4 = distSq(p1, p4); // from p1 to p4
 
    if (d2 == 0 || d3 == 0 || d4 == 0)   
        return false;
 
    // If lengths if (p1, p2) and (p1, p3) are same, then
    // following conditions must met to form a square.
    // 1) Square of length of (p1, p4) is same as twice
    // the square of (p1, p2)
    // 2) Square of length of (p2, p3) is same
    // as twice the square of (p2, p4)
    if (d2 == d3 && 2 * d2 == d4
        && 2 * distSq(p2, p4) == distSq(p2, p3))
    {
        return true;
    }
 
    // The below two cases are similar to above case
    if (d3 == d4 && 2 * d3 == d2
        && 2 * distSq(p3, p2) == distSq(p3, p4))
    {
        return true;
    }
    if (d2 == d4 && 2 * d2 == d3
        && 2 * distSq(p2, p3) == distSq(p2, p4))
    {
        return true;
    }
    return false;
}
 
// Driver code
public static void Main(String[] args)
{
    Point p1 = new Point(20, 10), p2 = new Point(10, 20),
        p3 = new Point(20, 20), p4 = new Point(10, 10);
    Console.WriteLine(isSquare(p1, p2, p3, p4) == true ? "Yes" : "No");
}
}
 
// This code is contributed by 29AjayKumar


Javascript




<script>
// JavaScript program to check if four given points form a square or not.
 
// A utility function to find square of distance
// from point 'p' to point 'q'
function distSq( p, q){
    return (p.x - q.x) * (p.x - q.x) + (p.y - q.y) * (p.y - q.y);
}
 
// This function returns true if (p1, p2, p3, p4) form a
// square, otherwise false
function isSquare(p1,  p2,  p3, p4){
    let d2 = distSq(p1, p2); // from p1 to p2
    let d3 = distSq(p1, p3); // from p1 to p3
    let d4 = distSq(p1, p4); // from p1 to p4
 
    if (d2 == 0 || d3 == 0 || d4 == 0)   
        return false;
 
    // If lengths if (p1, p2) and (p1, p3) are same, then
    // following conditions must met to form a square.
    // 1) Square of length of (p1, p4) is same as twice
    // the square of (p1, p2)
    // 2) Square of length of (p2, p3) is same
    // as twice the square of (p2, p4)
 
    if (d2 == d3 && 2 * d2 == d4
        && 2 * distSq(p2, p4) == distSq(p2, p3)) {
        return true;
    }
 
    // The below two cases are similar to above case
    if (d3 == d4 && 2 * d3 == d2
        && 2 * distSq(p3, p2) == distSq(p3, p4)) {
        return true;
    }
    if (d2 == d4 && 2 * d2 == d3
        && 2 * distSq(p2, p3) == distSq(p2, p4)) {
        return true;
    }
 
    return false;
}
 
// Driver program to test above function
let p1 = { x:20, y:10 }
let p2 = { x:10, y:20 }
let p3 = { x:20, y:20 }
let p4 = { x:10, y:10 }
isSquare(p1, p2, p3, p4) ? document.write("Yes") : document.write("No");
 
// This code is contributed by rohitsingh07052.
</script>


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: 

 



Similar Reads

Find Four points such that they form a square whose sides are parallel to x and y axes
Given 'n' pair of points, the task is to find four points such that they form a square whose sides are parallel to x and y axes or print "No such square" otherwise. If more than one square is possible then choose the one with the maximum area. Examples: Input : n = 6, points = (1, 1), (4, 4), (3, 4), (4, 3), (1, 4), (4, 1)Output : side of the squar
12 min read
Check if it is possible to travel all points in given time by moving in adjacent four directions
Given 3 arrays X[], Y[], and T[] all of the size N where X[i] and Y[i] represent the i-th coordinate and T[i] represents the time in seconds. Find it is possible to reach all the coordinates (X[i], Y[i]) in time T[i] from starting coordinates (0, 0). The pointer can move in four directions ( x +1, y ), ( x − 1, y ), ( x, y + 1) and (x, y − 1). From
13 min read
Check whether four points make a parallelogram
Given four points in a 2-dimensional space we need to find out whether they make a parallelogram or not.   A parallelogram has four sides. Two opposite sides are parallel and are of same lengths.   Examples: Points = [(0, 0), (4, 0), (1, 3), (5, 3)]Above points make a parallelogram.Points = [(0, 0), (2, 0), (4, 0), (2, 2)]Above points does not make
15+ min read
Check if four segments form a rectangle
We are given four segments as a pair of coordinates of their end points. We need to tell whether those four line segments make a rectangle or not. Examples: Input : segments[] = [(4, 2), (7, 5), (2, 4), (4, 2), (2, 4), (5, 7), (5, 7), (7, 5)] Output : Yes Given these segment make a rectangle of length 3X2. Input : segment[] = [(7, 0), (10, 0), (7,
9 min read
Find the point on X-axis from given N points having least Sum of Distances from all other points
Given an array arr[] consisting of N integers, denoting N points lying on the X-axis, the task is to find the point which has the least sum of distances from all other points. Example: Input: arr[] = {4, 1, 5, 10, 2} Output: (4, 0) Explanation: Distance of 4 from rest of the elements = |4 - 1| + |4 - 5| + |4 - 10| + |4 - 2| = 12 Distance of 1 from
11 min read
Count of obtuse angles in a circle with 'k' equidistant points between 2 given points
A circle is given with k equidistant points on its circumference. 2 points A and B are given in the circle. Find the count of all obtuse angles (angles larger than 90 degree) formed from /_ACB, where C can be any point in circle other than A or B. Note : A and B are not equal. A < B. Points are between 1 and K(both inclusive). Examples : Input :
5 min read
Euler's Four Square Identity
According to Euler's four square identity, the product of any two numbers a and b can be expressed as a sum of four squares if a and b both can individually be expressed as the sum of four squares.Mathematically, if a = [Tex]c1^2 + c2^2 + c3^2 + c4^2 [/Tex]and b = [Tex]d1^2 + d2^2 + d3^2 + d4^2 [/Tex]Then, a * b = [Tex]e1^2 + e2^2 + e3^2 + e4^2 [/T
15+ min read
Find the area of the shaded region formed by the intersection of four semicircles in a square
Given the length of the side of a square a, the task is to find the area of the shaded region formed by the intersection of four semicircles in a square as shown in the image below: Examples: Input: a = 10 Output: 57Input: a = 19 Output: 205.77 Approach: Area of the shaded region will be: Area(semicircle1) + Area(semicircle2) + Area(semicircle3) +
4 min read
Check if the given 2-D points form T-shape or not
Given the coordinates of 5 2-dimensional points, check if they form a closed T shape. Print 'Yes' if they form T shape and 'No' otherwise. Note: Coordinates should be distinct and integers.There are 4-types of T shaped formations possible according to the given conditions: Examples: Input: [[7, 5], [8, 5], [6, 5], [7, 7], [7, 6]] Output: Yes Input:
12 min read
Check if given string can be split into four distinct strings
Given a string, the task is to check if we can split it into 4 strings such that each string is non-empty and different from the other. Examples: Input : str[] = "geeksforgeeks"Output : Yes"geeks", "for", "gee", "ks" are four distinct strings that can form fromgiven string.Input : str[] = "aaabb"Output : NoRecommended PracticeSplit the stringTry It
7 min read
Check if given four integers (or sides) make rectangle
Given four positive integers, determine if there's a rectangle such that the lengths of its sides are a, b, c and d (in any order).Examples : Input : 1 1 2 2Output : Yes Input : 1 2 3 4Output : No Approach 1:- We will check, if any of the two integers are equal and make sure rest of two are also equal using few if else conditions. [GFGTABS] C++ //
7 min read
Ways to choose three points with distance between the most distant points <= L
Given a set of n distinct points x1, x2, x3... xn all lying on the X-axis and an integer L, the task is to find the number of ways of selecting three points such that the distance between the most distant points is less than or equal to L Note: Order is not important i.e the points {3, 2, 1} and {1, 2, 3} represent the same set of three points Exam
15+ min read
Steps required to visit M points in order on a circular ring of N points
Given an integer 'n', consider a circular ring containing 'n' points numbered from '1' to 'n' such that you can move in the following way : 1 -> 2 -> 3 -> ..... -> n -> 1 -> 2 -> 3 -> ...... Also, given an array of integers (of size 'm'), the task is to find the number of steps it'll take to get to every point in the array i
5 min read
Minimize the maximum distance between adjacent points after adding K points anywhere in between
Given an array arr[] of N integers representing the position of N points along a straight line and an integer K, the task is to find the minimum value of the maximum distance between adjacent points after adding K points anywhere in between, not necessarily on an integer position. Examples: Input: arr[] = {2, 4, 8, 10}, K = 1Output: 2Explanation: A
9 min read
Prime points (Points that split a number into two primes)
Given a n-digit number. Prime point is the index of the digit whose left and right side numbers are prime. Print all the prime points of the number. If no prime point exists print -1. Examples: Input : 2317 Output : 1 2 Explanation : Left and right side numbers of index point 1 are 2 and 17 respectively and both are primes. Left and right side numb
10 min read
Minimum number of points to be removed to get remaining points on one side of axis
We are given n points in a Cartesian plane. Our task is to find the minimum number of points that should be removed in order to get the remaining points on one side of any axis. Examples : Input : 4 1 1 2 2 -1 -1 -2 2 Output : 1 Explanation : If we remove (-1, -1) then all the remaining points are above x-axis. Thus the answer is 1. Input : 3 1 10
6 min read
Number of Integral Points between Two Points
Given two points p (x1, y1) and q (x2, y2), calculate the number of integral points lying on the line joining them. Input: x1 = 2, y1 = 2, x2 = 5, y2 = 5 Output: 2 Explanation: There are only 2 integral points on the line joining (2,2) and (5,5). The points are (3,3) and (4,4). Input: x1 = 1, y1 = 9, x2 = 8, y2 = 16 Output: 6 Explanation: There are
8 min read
Check if a number is a perfect square having all its digits as a perfect square
Given an integer N, the task is to check if the given number is a perfect square having all its digits as a perfect square or not. If found to be true, then print “Yes”. Otherwise, print “No”.Examples: Input: N = 144 Output: Yes Explanation: The number 144 is a perfect square and also the digits of the number {1(= 12, 4(= 22} is also a perfect squa
11 min read
Check if a number is perfect square without finding square root
Check whether a number is a perfect square or not without finding its square root. Examples: Input: n = 36 Output: Yes Input: n = 12 Output: No Recommended PracticeCheck perfect squareTry It! Method 1:The idea is to run a loop from i = 1 to floor(sqrt(n)) and then check if squaring it makes n. Below is the implementation: C/C++ Code // C++ program
9 min read
Check if the given point lies inside given N points of a Convex Polygon
Given coordinates of the N points of a Convex Polygon. The task is to check if the given point (X, Y) lies inside the polygon. Examples: Input: N = 7, Points: {(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)}, Query: X = 3, Y = 2 Below is the image of plotting of the given points: Output: YES Input: N = 7, Points: {(1, 1), (2, 1), (3, 1), (4
15 min read
Count integers whose square lie in given range and digits are perfect square
Given two integers L and R. Then the task is to output the count of integers X, such that L â‰Ī X2 â‰Ī R and X2 only consist of digits, which are perfect squares. Examples: Input: L = 167, R = 456Output: 2Explanation: Two numbers are 20 and 21, Their squares are 400 and 441 respectively. It can be verified that squares of both 20 and 21 are in the rang
13 min read
Forming triangles using points on a square
Given a square with N points on each side of the square and none of these points co-incide with the corners of the square. The task is to calculate the total number of triangles that can be formed using these 4 * N points (N points on each side of the square) as vertices of the triangle.Examples: Input: N = 1 Output: 4 There is one point on each si
3 min read
Minimum sum obtained from groups of four elements from the given array
Given an array arr[] of N integers where N % 4 = 0, the task is to divide the integers into groups of four such that when the combined sum of the maximum two elements from all the groups is taken, it is minimum possible. Print the minimized sum.Examples: Input: arr[] = {1, 1, 2, 2} Output: 4 The only group will be {1, 1, 2, 2}. 2 + 2 = 4Input: arr[
5 min read
Find the prime P using given four integers
Given four integers X, Y, X2%P, Y2%P, where P is a prime number. The task is to find prime P. Note: Answer always exists.Examples: Input : X = 3, XsqmodP = 0, Y = 5, YsqmodP = 1 Output : 3 When x = 3, x2 = 9, and 9 modulo P is 0. So possible value of p is 3 When x = 5, x2 = 25, and 25 modulo P is 1. So possible value of p is 3Input : X = 4, XsqmodP
7 min read
Number of digits in the nth number made of given four digits
Find the number of digits in the nth number constructed by using 6, 1, 4, and 9 as the only digits in the ascending order. First few numbers constructed by using only 6, 1, 4, and 9 as digits in ascending order would be: 1, 6, 4, 9, 11, 14, 16, 19, 41, 44, 46, 49, 61, 64, 66, 69, 91, 94, 96, 99, 111, 114, 116, 119 and so on. Examples: Input : 6Outp
13 min read
Count quadruples from four sorted arrays whose sum is equal to a given value x
Given four sorted arrays each of size n of distinct elements. Given a value x. The problem is to count all quadruples(group of four numbers) from all the four arrays whose sum is equal to x.Note: The quadruple has an element from each of the four arrays. Examples: Input : arr1 = {1, 4, 5, 6}, arr2 = {2, 3, 7, 8}, arr3 = {1, 4, 6, 10}, arr4 = {2, 4,
15+ min read
Find four elements that sum to a given value | Set 3 (Hashmap)
Given an array of integers, Check if there exist four elements at different indexes in the array whose sum is equal to a given value k. For example, if the given array is {1 5 1 0 6 0} and k = 7, then your function should print "YES" as (1+5+1+0=7). Examples: Input : arr[] = {1 5 1 0 6 0} k = 7 Output : YES Input : arr[] = {38 7 44 42 28 16 10 37 3
7 min read
Print maximum number of ‘A’ using given four keys
Imagine you have a special keyboard with the following keys: Key 1: Prints 'A' on screenKey 2: (ctrl-A): Select screenKey 3: (ctrl-C): Copy selection to bufferKey 4: (ctrl-V): Print buffer on screen appending it after what has already been printed. If you can only press the keyboard for N times (with the above four keys), write a program to produce
11 min read
How to print maximum number of A's using given four keys
This is a famous interview question asked in Google, Paytm and many other company interviews. Below is the problem statement. Imagine you have a special keyboard with the following keys: Key 1: Prints 'A' on screenKey 2: (Ctrl-A): Select screenKey 3: (Ctrl-C): Copy selection to bufferKey 4: (Ctrl-V): Print buffer on screen appending it after what h
15+ min read
Find four elements that sum to a given value | Two-Pointer approach
Given an array arr of integers of size N and a target number, the task is to find all unique quadruplets in it, whose sum is equal to the target number. Examples: Input: arr[] = {4, 1, 2, -1, 1, -3], target = 1 Output: [[-3, -1, 1, 4], [-3, 1, 1, 2]] Explanation: Both the quadruplets sum equals to target. Input: arr[] = {2, 0, -1, 1, -2, 2}, target
11 min read
Article Tags :