Skip to content
Related Articles
Open in App
Not now

Related Articles

Count of Squares that are parallel to the coordinate axis from the given set of N points

Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 16 Sep, 2022
Improve Article
Save Article

Given an array of points points[] in a cartesian coordinate system, the task is to find the count of the squares that are parallel to the coordinate axis. Examples:

Input:points[] = {(0, 0), (0, 2), (2, 0), (2, 2), (1, 1)} Output: 1 Explanation: As the points (0, 0), (0, 2), (2, 0), (2, 2) forms square which is parallel to the X-axis and Y-axis, Hence the count of such squares is 1. Input:points[] = {(2, 0), (0, 2), (2, 2), (0, 0), (-2, 2), (-2, 0)} Output: 2 Explanation: As the points (0, 0), (0, 2), (2, 0), (2, 2) forms one square, whereas points (0, 0), (0, 2), (-2, 0), (-2, 2) forms other square which is parallel to the X-axis and Y-axis, Hence the count of such squares is 2.

Approach: The idea is to choose two points from the array of points such that these two points are parallel to co-ordinate axis and then find other two points of the square with the help of the distance between the points. If those points exist in the array then, there is one such possible square. Below is the implementation of the above approach: 

C++




// C++ implementation to find count of Squares
// that are parallel to the coordinate axis
// from the given set of N points
 
#include <bits/stdc++.h>
using namespace std;
 
#define sz(x) int(x.size())
 
// Function to get distance
// between two points
int get_dis(pair<int, int> p1,
            pair<int, int> p2)
{
    int a = abs(p1.first - p2.first);
    int b = abs(p1.second - p2.second);
    return ((a * a) + (b * b));
}
 
// Function to check that points
// forms a square and parallel to
// the co-ordinate axis
bool check(pair<int, int> p1,
           pair<int, int> p2,
           pair<int, int> p3,
           pair<int, int> p4)
{
 
    int d2 = get_dis(p1, p2);
    int d3 = get_dis(p1, p3);
    int d4 = get_dis(p1, p4);
    if (d2 == d3
        && 2 * d2 == d4
        && 2 * get_dis(p2, p4) == get_dis(p2, p3)) {
        return true;
    }
    if (d3 == d4
        && 2 * d3 == d2
        && 2 * get_dis(p3, p2) == get_dis(p3, p4)) {
        return true;
    }
    if (d2 == d4
        && 2 * d2 == d3
        && 2 * get_dis(p2, p3) == get_dis(p2, p4)) {
        return true;
    }
    return false;
}
 
// Function to find all the squares which is
// parallel to co-ordinate axis
int count(map<pair<int, int>, int> hash,
          vector<pair<int, int> > v, int n)
{
    int ans = 0;
    map<pair<int, int>, int> vis;
 
    // Loop to choose two points
    // from the array of points
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i == j)
                continue;
            pair<int, int> p1
                = make_pair(v[i].first,
                            v[j].second);
            pair<int, int> p2
                = make_pair(v[j].first,
                            v[i].second);
            set<pair<int, int> > s;
            s.insert(v[i]);
            s.insert(v[j]);
            s.insert(p1);
            s.insert(p2);
            if (sz(s) != 4)
                continue;
 
            // Condition to check if the
            // other points are present in the map
            if (hash.find(p1) != hash.end()
                && hash.find(p2) != hash.end()) {
                if ((!vis[v[i]] || !vis[v[j]]
                     || !vis[p1] || !vis[p2])
                    && (check(v[i], v[j], p1, p2))) {
 
                    vis[v[i]] = 1;
                    vis[v[j]] = 1;
                    vis[p1] = 1;
                    vis[p2] = 1;
                    ans++;
                }
            }
        }
    }
    cout << ans;
    return ans;
}
 
// Function to Count the number of squares
void countOfSquares(vector<pair<int, int> > v, int n)
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
 
    map<pair<int, int>, int> hash;
 
    // Declaring iterator to a vector
    vector<pair<int, int> >::iterator ptr;
 
    // Adding the points to hash
    for (ptr = v.begin(); ptr < v.end(); ptr++)
        hash[*ptr] = 1;
 
    // Count the number of squares
    count(hash, v, n);
}
 
// Driver Code
int main()
{
 
    int n = 5;
    vector<pair<int, int> > v;
    v.push_back(make_pair(0, 0));
    v.push_back(make_pair(0, 2));
    v.push_back(make_pair(2, 0));
    v.push_back(make_pair(2, 2));
    v.push_back(make_pair(0, 1));
 
    // Function call
    countOfSquares(v, n);
    return 0;
}

Java




// Java implementation to find count of Squares
// that are parallel to the coordinate axis
// from the given set of N points
import java.util.*;
 
class GFG
{
 
  // Function to get distance
  // between two points
  static int get_dis(int[] p1, int[] p2)
  {
    int a = Math.abs(p1[0] - p2[0]);
    int b = Math.abs(p1[1] - p2[1]);
    return ((a * a) + (b * b));
  }
 
  // Function to check that points
  // forms a square and parallel to
  // the co-ordinate axis
  static boolean check(int[] p1, int[] p2, int[] p3, int[] p4)
  {
 
    int d2 = get_dis(p1, p2);
    int d3 = get_dis(p1, p3);
    int d4 = get_dis(p1, p4);
    if (d2 == d3
        && 2 * d2 == d4
        && 2 * get_dis(p2, p4) == get_dis(p2, p3)) {
      return true;
    }
    if (d3 == d4
        && 2 * d3 == d2
        && 2 * get_dis(p3, p2) == get_dis(p3, p4)) {
      return true;
    }
    if (d2 == d4
        && 2 * d2 == d3
        && 2 * get_dis(p2, p3) == get_dis(p2, p4)) {
      return true;
    }
    return false;
  }
 
  // Function to find all the squares which is
  // parallel to co-ordinate axis
  static int count(HashMap<String, Integer> hash, int[][] v, int n)
  {
    int ans = 1;
    HashMap<String, Integer> vis = new HashMap<String, Integer>();
 
    // Loop to choose two points
    // from the array of points
    for (var i = 0; i < n; i++) {
      for (var j = 0; j < n; j++) {
        if (i == j)
          continue;
        String v1 = String.valueOf(v[i][0]) + "#" + String.valueOf(v[i][1]);
        String v2 = String.valueOf(v[j][0]) + "#" + String.valueOf(v[j][1]);
        String p1 = String.valueOf(v[i][0]) + "#" + String.valueOf(v[j][1]);
        String p2 = String.valueOf(v[j][0]) + "#" + String.valueOf(v[i][1]);
 
        HashSet<String> s = new HashSet<String>();
        s.add(v1);
        s.add(v2);
        s.add(p1);
        s.add(p2);
        if (s.size() != 4)
          continue;
 
        // Condition to check if the
        // other points are present in the map
        if (hash.containsKey(p1)
            && hash.containsKey(p2)) {
          if ((!vis.containsKey(v1) || !vis.containsKey(v2) || !vis.containsKey(p1) || !vis.containsKey(p2) )
 
              && (check(v[i], v[j], new int[] {v[i][0], v[j][1]}, new int[] {v[j][0], v[i][1]}))) {
 
            vis.put(v1,  1);
            vis.put(v2,  1);
            vis.put(p1,  1);
            vis.put(p2,  1);
            ans++;
          }
        }
      }
    }
    System.out.println(ans);
    return ans;
  }
 
  // Function to Count the number of squares
  static void countOfSquares(int[][] v, int n)
  {
    HashMap<String, Integer> hash = new HashMap<String, Integer>();
 
 
    // Adding the points to hash
    for (int[] ptr : v)
    {
      hash.put(String.valueOf(ptr[0]) + "#" + String.valueOf(ptr[1]),  1);
    }
 
    // Count the number of squares
    count(hash, v, n);
  }
 
 
  public static void main(String[] args)
  {
    // Driver Code
    int n = 5;
    int[][] v = new int[5][];
    v[0] = new int[] {0, 0};
    v[1] = new int[] {2, 0};
    v[2] = new int[] {2, 0};
    v[3] = new int[] {2, 2};
    v[4] = new int[] {0, 1};
 
    // Function call
    countOfSquares(v, n);   
 
  }
}
 
// This code is contributed by phasing17

Python3




# Python implementation to find count of Squares
# that are parallel to the coordinate axis
# from the given set of N points
 
# Function to get distance
# between two points
def get_dis(p1, p2):
 
    a = abs(p1[0] - p2[0]);
    b = abs(p1[1] - p2[1]);
    return ((a * a) + (b * b));
 
# Function to check that points
# forms a square and parallel to
# the co-ordinate axis
def check(p1, p2, p3, p4):
 
    d2 = get_dis(p1, p2);
    d3 = get_dis(p1, p3);
    d4 = get_dis(p1, p4);
    if (d2 == d3  and 2 * d2 == d4 and 2 * get_dis(p2, p4) == get_dis(p2, p3)):
        return True;
     
    if (d3 == d4 and 2 * d3 == d2 and 2 * get_dis(p3, p2) == get_dis(p3, p4)):
        return True;
     
    if (d2 == d4 and 2 * d2 == d3 and 2 * get_dis(p2, p3) == get_dis(p2, p4)) :
        return True;
     
    return False;
 
# Function to find all the squares which is
# parallel to co-ordinate axis
def count(hash1, v, n):
 
    ans = 0;
    vis = dict();
 
    # Loop to choose two points
    # from the array of points
    for i in range(n):
        for j in range(n):
            if (i == j):
                continue;
            v1 = (v[i][0], v[i][1])
            v2 = (v[j][0], v[j][1])
            p1 = (v[i][0], v[j][1]);
            p2 = (v[j][0], v[i][1]);
            s = set()
            s.add(v1);
            s.add(v2);
            s.add(p1);
            s.add(p2);
            if (len(s) != 4):
                continue;
     
            # Condition to check if the
            # other points are present in the map
            if p1 in hash1 and p2 in hash1:
                if v1 not in vis or v2 not in vis or p1 not in vis or p2 not in vis:
                    if (check(v[i], v[j], [v[i][0], v[j][1]], [v[j][0], v[i][1]])):
                        vis[v1] = 1;
                        vis[v2] = 1;
                        vis[p1] = 1;
                        vis[p2] = 1;
             
                        ans += 1
    print(ans);
    return ans;
 
# Function to Count the number of squares
def countOfSquares(v, n):
 
    hash1 = dict();
 
 
    # Adding the points to hash1
    for ptr in v:
        hash1[(ptr[0], ptr[1])] = 1;
 
    # Count the number of squares
    count(hash1, v, n);
 
# Driver Code
n = 5;
v = [ [0, 0], [0, 2], [2, 0], [2, 2], [0, 1] ];
 
# Function call
countOfSquares(v, n);
 
# This code is contributed by phasing17

C#




// c# implementation to find count of Squares
// that are parallel to the coordinate axis
// from the given set of N points
using System;
using System.Collections.Generic;
 
public class GFG
{
 
    // Function to get distance
    // between two points
    static int get_dis(int[] p1, int[] p2)
    {
        int a = Math.Abs(p1[0] - p2[0]);
        int b = Math.Abs(p1[1] - p2[1]);
        return ((a * a) + (b * b));
    }
     
    // Function to check that points
    // forms a square and parallel to
    // the co-ordinate axis
    static bool check(int[] p1, int[] p2, int[] p3, int[] p4)
    {
     
        int d2 = get_dis(p1, p2);
        int d3 = get_dis(p1, p3);
        int d4 = get_dis(p1, p4);
        if (d2 == d3
            && 2 * d2 == d4
            && 2 * get_dis(p2, p4) == get_dis(p2, p3)) {
            return true;
        }
        if (d3 == d4
            && 2 * d3 == d2
            && 2 * get_dis(p3, p2) == get_dis(p3, p4)) {
            return true;
        }
        if (d2 == d4
            && 2 * d2 == d3
            && 2 * get_dis(p2, p3) == get_dis(p2, p4)) {
            return true;
        }
        return false;
    }
     
    // Function to find all the squares which is
    // parallel to co-ordinate axis
    static int count(Dictionary<string, int> hash, int[][] v, int n)
    {
        int ans = 1;
        Dictionary<string, int> vis = new Dictionary<string, int>();
     
        // Loop to choose two points
        // from the array of points
        for (var i = 0; i < n; i++) {
            for (var j = 0; j < n; j++) {
                if (i == j)
                    continue;
            string v1 = Convert.ToString(v[i][0]) + "#" + Convert.ToString(v[i][1]);
            string v2 = Convert.ToString(v[j][0]) + "#" + Convert.ToString(v[j][1]);
            string p1 = Convert.ToString(v[i][0]) + "#" + Convert.ToString(v[j][1]);
            string p2 = Convert.ToString(v[j][0]) + "#" + Convert.ToString(v[i][1]);
             
            HashSet<string> s = new HashSet<string>();
                s.Add(v1);
                s.Add(v2);
                s.Add(p1);
                s.Add(p2);
                if (s.Count != 4)
                    continue;
     
                // Condition to check if the
                // other points are present in the map
                if (hash.ContainsKey(p1)
                    && hash.ContainsKey(p2)) {
                    if ((!vis.ContainsKey(v1) || !vis.ContainsKey(v2) || !vis.ContainsKey(p1) || !vis.ContainsKey(p2) )
                     
                        && (check(v[i], v[j], new[] {v[i][0], v[j][1]}, new [] {v[j][0], v[i][1]}))) {
     
                        vis[v1] = 1;
                        vis[v2] = 1;
                        vis[p1] = 1;
                        vis[p2] = 1;
                        ans++;
                    }
                }
            }
        }
        Console.WriteLine(ans);
        return ans;
    }
     
    // Function to Count the number of squares
    static void countOfSquares(int[][] v, int n)
    {
        Dictionary<string, int> hash = new Dictionary<string, int>();
     
     
        // Adding the points to hash
        foreach (int[] ptr in v)
        {
            hash[Convert.ToString(ptr[0]) + "#" + Convert.ToString(ptr[1])] = 1;
        }
     
        // Count the number of squares
        count(hash, v, n);
    }
     
   
    public static void Main(string[] args)
    {
        // Driver Code
        int n = 5;
        int[][] v = new int[5][];
        v[0] = new [] {0, 0};
        v[1] = new [] {2, 0};
        v[2] = new [] {2, 0};
        v[3] = new [] {2, 2};
        v[4] = new [] {0, 1};
 
        // Function call
        countOfSquares(v, n);   
         
    }
}
 
// This code is contributed by phasing17

Javascript




// JS implementation to find count of Squares
// that are parallel to the coordinate axis
// from the given set of N points
 
 
function sz(x)
{
    return x.length;
}
 
// Function to get distance
// between two points
function get_dis(p1, p2)
{
    let a = Math.abs(p1[0] - p2[0]);
    let b = Math.abs(p1[1] - p2[1]);
    return ((a * a) + (b * b));
}
 
// Function to check that points
// forms a square and parallel to
// the co-ordinate axis
function check(p1, p2, p3, p4)
{
 
    let d2 = get_dis(p1, p2);
    let d3 = get_dis(p1, p3);
    let d4 = get_dis(p1, p4);
    if (d2 == d3
        && 2 * d2 == d4
        && 2 * get_dis(p2, p4) == get_dis(p2, p3)) {
        return true;
    }
    if (d3 == d4
        && 2 * d3 == d2
        && 2 * get_dis(p3, p2) == get_dis(p3, p4)) {
        return true;
    }
    if (d2 == d4
        && 2 * d2 == d3
        && 2 * get_dis(p2, p3) == get_dis(p2, p4)) {
        return true;
    }
    return false;
}
 
// Function to find all the squares which is
// parallel to co-ordinate axis
function count(hash, v, n)
{
    let ans = 0;
    let vis = {};
 
    // Loop to choose two points
    // from the array of points
    for (var i = 0; i < n; i++) {
        for (var j = 0; j < n; j++) {
            if (i == j)
                continue;
        let v1 = v[i][0] + "#" + v[i][1]
        let v2 = v[j][0] + "#" + v[j][1]
           let p1 = v[i][0] + "#" + v[j][1];
        let p2 = v[j][0] + "#" + v[i][1];
        let s = new Set();
            s.add(v1);
            s.add(v2);
            s.add(p1);
            s.add(p2);
            if (s.size != 4)
                continue;
 
            // Condition to check if the
            // other points are present in the map
            if (hash.hasOwnProperty(p1)
                && hash.hasOwnProperty(p2)) {
                if ((!vis.hasOwnProperty(v1) || !vis.hasOwnProperty(v2) || !vis.hasOwnProperty(p1) || !vis.hasOwnProperty(p2) )
                 
                    && (check(v[i], v[j], [v[i][0], v[j][1]], [v[j][0], v[i][1]]))) {
 
                    vis[v1] = 1;
                    vis[v2] = 1;
                    vis[p1] = 1;
                    vis[p2] = 1;
                    ans++;
                }
            }
        }
    }
    console.log(ans);
    return ans;
}
 
// Function to Count the number of squares
function countOfSquares(v, n)
{
    let hash = {};
 
 
    // Adding the points to hash
    for (var ptr of v)
    {
        hash[ptr[0] + "#" + ptr[1]] = 1;
    }
 
 
    // Count the number of squares
    count(hash, v, n);
}
 
 
// Driver Code
let n = 5;
let v = [ [0, 0], [0, 2], [2, 0], [2, 2], [0, 1] ];
 
// Function call
countOfSquares(v, n);
 
 
// This code is contributed by phasing17

Output:

1

Performance Analysis:

  • Time Complexity: As in the above approach, there are two loops which takes O(N2) time, Hence the Time Complexity will be O(N2).
  • Auxiliary Space Complexity: As in the above approach, there is extra space used, Hence the auxiliary space complexity will be O(N).

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!