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.
Input : n = 6, points = (1, 1), (4, 4), (3, 4), (4, 3), (1, 4), (4, 1)
side of the square is : 3, points of the square are 1, 1 4, 1 1, 4 4, 4
Explanation: The points 1, 1 4, 1 1, 4 4, 4 form a square of side 3
Input :n= 6, points= (1, 1), (4, 5), (3, 4), (4, 3), (7, 4), (3, 1)
Output :No such square
Simple approach: Choose all possible pairs of points with four nested loops and then see if the points form a square which is parallel to principal axes. If yes then check if it is the largest square so far in terms of the area and store the result, and then display the result at the end of the program.
Time Complexity: O(N^4)
Efficient Approach: Create a nested loop for top right and bottom left corner of the square and form a square with those two points, then check if the other two points which were assumed actually exist. To check if a point exists or not, create a map and store the points in the map to reduce the time to check whether the points exist. Also, keep in check the largest square by area so far and print it in the end.
Below is the implementation of the above approach:
Side of the square is : 3, points of the square are 1, 1 4, 1 1, 4 4, 4
Time Complexity: O(N^2)
- How to check if given four points form a square
- Find whether only two parallel lines contain all coordinates points or not
- Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)
- Probability of cutting a rope into three pieces such that the sides form a triangle
- Program to check if the points are parallel to X axis or Y axis
- Check if the given 2-D points form T-shape or not
- Find other two sides of a right angle triangle
- Number of triangles formed by joining vertices of n-sided polygon with two common sides and no common sides
- Find other two sides and angles of a right angle triangle
- Find all sides of a right angled triangle from given hypotenuse and area | Set 1
- Find area of triangle if two vectors of two adjacent sides are given
- Find area of parallelogram if vectors of two adjacent sides are given
- Number of ways to arrange 2*N persons on the two sides of a table with X and Y persons on opposite sides
- Area of triangle formed by the axes of co-ordinates and a given straight line
- Find K Closest Points to the Origin
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.