Open In App

# 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 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 the top right and bottom left corner of the square and form a square with those two points, then check if the other two points were assumed actually exist. To check if a point exists or not, create a map and store the points on 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:

## CPP

 `// C++ implemenataion of the above approach``#include ``using` `namespace` `std;` `// find the largest square``void` `findLargestSquare(``long` `long` `int` `points[][2], ``int` `n)``{``    ``// map to store which points exist``    ``map, ``int``> m;` `    ``// mark the available points``    ``for` `(``int` `i = 0; i < n; i++) {``        ``m[make_pair(points[i][0], points[i][1])]++;``    ``}``    ``long` `long` `int` `side = -1, x = -1, y = -1;` `    ``// a nested loop to choose the opposite corners of square``    ``for` `(``int` `i = 0; i < n; i++) {` `        ``// remove the chosen point``        ``m[make_pair(points[i][0], points[i][1])]--;``        ``for` `(``int` `j = 0; j < n; j++) {` `            ``// remove the chosen point``            ``m[make_pair(points[j][0], points[j][1])]--;` `            ``// check if the other two points exist``            ``if` `(i != j``                  ``&& (points[i][0]-points[j][0]) == (points[i][1]-points[j][1])){``                ``if` `(m[make_pair(points[i][0], points[j][1])] > 0``                     ``&& m[make_pair(points[j][0], points[i][1])] > 0) {` `                    ``// if the square is largest then store it``                    ``if` `(side < ``abs``(points[i][0] - points[j][0])``                         ``|| (side == ``abs``(points[i][0] - points[j][0])``                            ``&& ((points[i][0] * points[i][0]``                                   ``+ points[i][1] * points[i][1])``                                      ``< (x * x + y * y)))) {``                        ``x = points[i][0];``                        ``y = points[i][1];``                        ``side = ``abs``(points[i][0] - points[j][0]);``                    ``}``                ``}``            ``}` `            ``// add the removed point``            ``m[make_pair(points[j][0], points[j][1])]++;``        ``}` `        ``// add the removed point``        ``m[make_pair(points[i][0], points[i][1])]++;``    ``}` `    ``// display the largest square``    ``if` `(side != -1)``        ``cout << ``"Side of the square is : "` `<< side``             ``<< ``", \npoints of the square are "` `<< x << ``", "` `<< y``             ``<< ``" "``             ``<< (x + side) << ``", "` `<< y``             ``<< ``" "``             ``<< (x) << ``", "` `<< (y + side)``             ``<< ``" "``             ``<< (x + side) << ``", "` `<< (y + side) << endl;``    ``else``        ``cout << ``"No such square"` `<< endl;``}` `//Driver code``int` `main()``{``    ``int` `n = 6;` `    ``// given points``    ``long` `long` `int` `points[n][2]``      ``= { { 1, 1 }, { 4, 4 }, { 3, 4 }, { 4, 3 }, { 1, 4 }, { 4, 1 } };` `    ``// find the largest square``    ``findLargestSquare(points, n);` `    ``return` `0;``}`

## Java

 `// Java implemenataion of the above approach``import` `java.util.*;``import` `java.util.Arrays.*;` `// Defining a class to implement equals and hashCode``// methods for int[] as key``class` `Array {``    ``public` `Integer[] arrayInstance;` `    ``public` `void` `setArray(Integer[] a)``    ``{``        ``this``.arrayInstance = a;``    ``}` `    ``@Override` `public` `int` `hashCode()``    ``{``        ``final` `int` `prime = ``31``;``        ``int` `result = ``1``;``        ``result = prime * result``                 ``+ Arrays.deepHashCode(arrayInstance);``        ``return` `result;``    ``}` `    ``@Override` `public` `boolean` `equals(Object obj)``    ``{``        ``if` `(``this` `== obj)``            ``return` `true``;``        ``if` `(obj == ``null``)``            ``return` `false``;``        ``if` `(getClass() != obj.getClass())``            ``return` `false``;``        ``Array other = (Array)obj;``        ``if` `(!Arrays.deepEquals(arrayInstance,``                               ``other.arrayInstance))``            ``return` `false``;``        ``return` `true``;``    ``}``}` `class` `GFG {``    ``// find the largest square``    ``static` `void` `findLargestSquare(``int``[][] points, ``int` `n)``    ``{``        ``// map to store which points exist``        ``Map m``            ``= ``new` `HashMap();` `        ``// mark the available points``        ``for` `(``int` `i = ``0``; i < n; i++) {``            ``Integer[] l1 = { points[i][``0``], points[i][``1``] };``            ``Array a1 = ``new` `Array();``            ``a1.setArray(l1);``            ``if` `(!m.containsKey(a1))``                ``m.put(a1, ``0``);``            ``m.put(a1, m.get(a1) + ``1``);``        ``}``        ``int` `side = -``1``, x = -``1``, y = -``1``;` `        ``// a nested loop to choose the opposite corners of``        ``// square``        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``// remove the chosen point``            ``Integer[] l1 = { points[i][``0``], points[i][``1``] };``            ``Array a1 = ``new` `Array();``            ``a1.setArray(l1);``            ``m.put(a1, m.get(a1) - ``1``);``            ``for` `(``int` `j = ``0``; j < n; j++) {` `                ``Integer[] l2``                    ``= { points[j][``0``], points[j][``1``] };``                ``Array a2 = ``new` `Array();``                ``a2.setArray(l2);``                ``// remove the chosen point``                ``m.put(a2, m.get(a2) - ``1``);` `                ``Integer[] l3``                    ``= { points[i][``0``], points[j][``1``] };``                ``Integer[] l4``                    ``= { points[j][``0``], points[i][``1``] };``                ``Array a3 = ``new` `Array();``                ``a3.setArray(l3);``                ``Array a4 = ``new` `Array();``                ``a4.setArray(l4);` `                ``// check if the other two points exist``                ``if` `(i != j``                    ``&& (points[i][``0``] - points[j][``0``])``                           ``== (points[i][``1``]``                               ``- points[j][``1``])) {``                    ``if` `(m.containsKey(a3)``                        ``&& m.containsKey(a4)) {` `                        ``// if the square is largest then``                        ``// store it``                        ``if` `(side < Math.abs(points[i][``0``]``                                            ``- points[j][``0``])``                            ``|| (side``                                    ``== Math.abs(``                                        ``points[i][``0``]``                                        ``- points[j][``0``])``                                ``&& ((points[i][``0``]``                                         ``* points[i][``0``]``                                     ``+ points[i][``1``]``                                           ``* points[i][``1``])``                                    ``< (x * x + y * y)))) {``                            ``x = points[i][``0``];``                            ``y = points[i][``1``];``                            ``side = Math.abs(points[i][``0``]``                                            ``- points[j][``0``]);``                        ``}``                    ``}``                ``}` `                ``// add the removed point``                ``m.put(a2, m.get(a2) + ``1``);``            ``}` `            ``// add the removed point``            ``m.put(a1, m.get(a1) + ``1``);``        ``}` `        ``// display the largest square``        ``if` `(side != -``1``)``            ``System.out.println(``                ``"Side of the square is : "` `+ side``                ``+ ``", \npoints of the square are "` `+ x + ``", "``                ``+ y + ``" "` `+ (x + side) + ``", "` `+ y + ``" "``                ``+ (x) + ``", "` `+ (y + side) + ``" "` `+ (x + side)``                ``+ ``", "` `+ (y + side));``        ``else``            ``System.out.println(``"No such square"``);``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `n = ``6``;` `        ``// given points``        ``int``[][] points = { { ``1``, ``1` `}, { ``4``, ``4` `}, { ``3``, ``4` `},``                           ``{ ``4``, ``3` `}, { ``1``, ``4` `}, { ``4``, ``1` `} };` `        ``// find the largest square``        ``findLargestSquare(points, n);``    ``}``}` `// This code is contributed by phasing17`

## Python3

 `# Python3 implemenataion of the above approach` `# find the largest square``def` `findLargestSquare(points,n):``    ` `    ``# map to store which points exist``    ``m ``=` `dict``()` `    ``# mark the available points``    ``for` `i ``in` `range``(n):``        ``m[(points[i][``0``], points[i][``1``])] ``=` `\``        ``m.get((points[i][``0``], points[i][``1``]), ``0``) ``+` `1` `    ``side ``=` `-``1``    ``x ``=` `-``1``    ``y ``=` `-``1` `    ``# a nested loop to choose the opposite corners of square``    ``for` `i ``in` `range``(n):` `        ``# remove the chosen point``        ``m[(points[i][``0``], points[i][``1``])]``-``=``1``        ``for` `j ``in` `range``(n):` `            ``# remove the chosen point``            ``m[(points[j][``0``], points[j][``1``])]``-``=``1` `            ``# check if the other two points exist``            ``if` `(i !``=` `j ``and` `(points[i][``0``]``-``points[j][``0``]) ``=``=` `\``                ``(points[i][``1``]``-``points[j][``1``])):``                ``if` `(m[(points[i][``0``], points[j][``1``])] > ``0` `and``                    ``m[(points[j][``0``], points[i][``1``])] > ``0``):` `                    ``# if the square is largest then store it``                    ``if` `(side < ``abs``(points[i][``0``] ``-` `points[j][``0``])``                        ``or` `(side ``=``=` `abs``(points[i][``0``] ``-` `points[j][``0``])``                            ``and` `((points[i][``0``] ``*` `points[i][``0``]``                                ``+` `points[i][``1``] ``*` `points[i][``1``])``                                    ``< (x ``*` `x ``+` `y ``*` `y)))):``                        ``x ``=` `points[i][``0``]``                        ``y ``=` `points[i][``1``]``                        ``side ``=` `abs``(points[i][``0``] ``-` `points[j][``0``])` `            ``# add the removed point``            ``m[(points[j][``0``], points[j][``1``])] ``+``=` `1` `        ``# add the removed point``        ``m[(points[i][``0``], points[i][``1``])] ``+``=` `1` `    ``# display the largest square``    ``if` `(side !``=` `-``1``):``        ``print``(``"Side of the square is : "``,side``            ``,``", \npoints of the square are "``,x,``", "``,y``            ``,``" "``            ``,(x ``+` `side),``", "``,y``            ``,``" "``            ``,(x),``", "``,(y ``+` `side)``            ``,``" "``            ``,(x ``+` `side),``", "``,(y ``+` `side))``    ``else``:``        ``print``(``"No such square"``)` `# Driver code``n ``=` `6` `# given points``points``=``[[ ``1``, ``1` `],[ ``4``, ``4` `],[ ``3``, ``4` `],[ ``4``, ``3` `],[ ``1``, ``4` `],[ ``4``, ``1` `] ]` `# find the largest square``findLargestSquare(points, n)` `# This code is contributed by mohit kumar 29`

## C#

 `// C# implemenataion of the above approach``using` `System;``using` `System.Collections.Generic;` `// Defining a class to implement Equals and GetHashCode``// methods for int[] as key``public` `class` `MyEqualityComparer : IEqualityComparer<``int``[]>``{``    ``// This method compares two int[] arrays``    ``public` `bool` `Equals(``int``[] x, ``int``[] y)``    ``{``        ``if` `(x.Length != y.Length)``        ``{``            ``return` `false``;``        ``}``        ``for` `(``int` `i = 0; i < x.Length; i++)``        ``{``            ``if` `(x[i] != y[i])``            ``{``                ``return` `false``;``            ``}``        ``}``        ``return` `true``;``    ``}` `    ``// This method generates a hashcode for an int[] key``    ``public` `int` `GetHashCode(``int``[] obj)``    ``{``        ``int` `result = 17;``        ``for` `(``int` `i = 0; i < obj.Length; i++)``        ``{``            ``unchecked``            ``{``                ``result = result * 23 + obj[i];``            ``}``        ``}``        ``return` `result;``    ``}``}` `class` `GFG``{``  ``// find the largest square``  ``static` `void` `findLargestSquare(``int``[,] points, ``int` `n)``  ``{``    ``// map to store which points exist``    ``Dictionary<``int``[], ``int``> m = ``new` `Dictionary<``int``[], ``int``>(``new` `MyEqualityComparer());` `    ``// mark the available points``    ``for` `(``int` `i = 0; i < n; i++) {``      ``int``[] l1 = {points[i, 0], points[i, 1]};``      ``if` `(!m.ContainsKey(l1))``        ``m[l1] = 0;``      ``m[l1]++;``    ``}``    ``int` `side = -1, x = -1, y = -1;` `    ``// a nested loop to choose the opposite corners of square``    ``for` `(``int` `i = 0; i < n; i++) {` `      ``// remove the chosen point``      ``int``[] l1= {points[i, 0], points[i, 1]};``      ``m[l1]--;``      ``for` `(``int` `j = 0; j < n; j++) {` `        ``int``[] l2 = {points[j,0], points[j,1]};``        ``// remove the chosen point``        ``m[l2]--;` `        ``int``[] l3 = {points[i,0], points[j,1]};``        ``int``[] l4 = {points[j,0], points[i,1]};` `        ``// check if the other two points exist``        ``if` `(i != j``            ``&& (points[i,0]-points[j,0]) == (points[i,1]-points[j,1])){``          ``if` `(m.ContainsKey(l3)``              ``&& m.ContainsKey(l4)) {` `            ``// if the square is largest then store it``            ``if` `(side < Math.Abs(points[i,0] - points[j,0])``                ``|| (side == Math.Abs(points[i,0] - points[j,0])``                    ``&& ((points[i,0] * points[i,0]``                         ``+ points[i,1] * points[i,1])``                        ``< (x * x + y * y)))) {``              ``x = points[i,0];``              ``y = points[i,1];``              ``side = Math.Abs(points[i,0] - points[j,0]);``            ``}``          ``}``        ``}` `        ``// add the removed point``        ``m[l2]++;``      ``}` `      ``// add the removed point``      ``m[l1]++;``    ``}` `    ``// display the largest square``    ``if` `(side != -1)``      ``Console.WriteLine(``"Side of the square is : "` `+ side +``                        ``", \npoints of the square are "` `+ x + ``", "` `+ y``                        ``+ ``" "``                        ``+ (x + side) + ``", "` `+ y``                        ``+ ``" "``                        ``+ (x) + ``", "` `+ (y + side)``                        ``+ ``" "``                        ``+ (x + side) + ``", "` `+ (y + side));``    ``else``      ``Console.WriteLine(``"No such square"``);``  ``}` `  ``//Driver code``  ``public` `static` `void` `Main(``string``[] args)``  ``{``    ``int` `n = 6;` `    ``// given points``    ``int``[,] points = { { 1, 1 }, { 4, 4 }, { 3, 4 }, { 4, 3 }, { 1, 4 }, { 4, 1 } };` `    ``// find the largest square``    ``findLargestSquare(points, n);` `  ``}``}`  `// This code is contributed by phasing17`

## Javascript

 `// JavaScript implemenataion of the above approach` `// find the largest square``function` `findLargestSquare(points, n)``{``    ``// map to store which points exist``    ``let m = ``new` `Map();` `    ``// mark the available points``    ``for` `(let i = 0; i < n; i++) {``        ``if``(m.has([points[i][0], points[i][1]].join())){``            ``m.set([points[i][0],  points[i][1]].join(), m.get([points[i][0], points[i][1]].join() + 1));``        ``}``        ``else``{``            ``m.set([points[i][0], points[i][1]].join(), 1);``        ``}``    ``}``    ``let side = -1, x = -1, y = -1;` `    ``// a nested loop to choose the opposite corners of square``    ``for` `(let i = 0; i < n; i++) {` `        ``// remove the chosen point``        ``m.set([points[i][0], points[i][1]].join(), m.get([points[i][0], points[i][1]].join()) - 1);` `        ``for` `(let j = 0; j < n; j++) {` `            ``// remove the chosen point``            ``m.set([points[j][0], points[j][1]].join(), m.get([points[j][0], points[j][1]].join()) - 1);` `            ``// check if the other two points exist``            ``if` `(i != j && (points[i][0]-points[j][0]) == (points[i][1]-points[j][1])){``                ``if` `(m.get([points[i][0], points[j][j]].join()) > 0 && m.get([points[j][0], points[i][1]].join()) > 0) {``                    ``// if the square is largest then store it``                    ``if` `(side < Math.abs(points[i][0] - points[j][0])``                         ``|| (side == Math.abs(points[i][0] - points[j][0]) && ((points[i][0] * points[i][0] + points[i][1] * points[i][1]) < (x * x + y * y)))) {``                        ``x = points[i][0];``                        ``y = points[i][1];``                        ``side = Math.abs(points[i][0] - points[j][0]);``                    ``}``                ``}``            ``}` `            ``// add the removed point``            ``m.set([points[j][0], points[j][1]].join(), m.get([points[j][0], points[j][1]].join()) + 1);``        ``}` `        ``// add the removed point``        ``m.set([points[i][0], points[i][1]].join(), m.get([points[i][0], points[i][1]].join()) + 1);``    ``}` `    ``// display the largest square``    ``if` `(side != -1){``        ``console.log(``"Side of the square is :"``, side, ``", "``);``        ``console.log(``"points of the square are"``, x, ``","``, y, x + side, ``","``, y, x, ``","``, y + side, x + side, ``","``, y + side);  ``    ``}``    ``else``        ``console.log(``"No such square"``);``}` `//Driver code``let n = 6;` `// given points``let points = [[1, 1 ],  [4, 4], [3, 4], [4, 3], [1, 4], [4, 1]];` `// find the largest square``findLargestSquare(points, n);` `// The code is contributed by Nidhi goel`

Output:

```Side of the square is : 3,
points of the square are 1, 1 4, 1 1, 4 4, 4```

Time Complexity: O(N^2)
Auxiliary Space: O(N)