Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Maximum number of overlapping rectangles with at least one common point

  • Last Updated : 01 Nov, 2021

Given four arrays x1[], x2[], y1[], y2[] of size N where (x1[i], y1[i]) denotes the left-bottom corner and (x2[i], y2[i]) right-top corner of a rectangle, the task is to find the maximum number of overlapping rectangles with at least one common point.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: N = 2 x1[] = {0, 50} y1[] = {0, 50} x2[] = {100, 60} y2[] = {100, 60}
Output: 2
Explanation: There are two rectangles {{0, 0}, {100, 100}}, {{50, 50}, {60, 60}} and both of them are intersecting as shown in the given figure below:



Input: N = 2 x1[] = {0, 100} y1[] = {0, 100} x2[] = {100, 200} y2[] = {100, 200}
Output: 1

Approach: The given problem can be solved by using the Greedy Approach which is based on the idea is that every rectangle on the coordinate plane has its own region and when multiple rectangles are added on the same plane they create intersections between each other. Therefore, to select the maximum number of rectangles overlapping on the common area, greedily choose the area of 1×1 unit as all overlapping areas will have at least this much block. Follow the steps below to solve the given problem:

  • Since there are N rectangles and each rectangle have 2 X-coordinates and 2 Y-coordinates. There will be a total of 2*N number of X -coordinates and Y-coordinates.
  • Therefore, create a vector of X and Y coordinates and push all the X’s and Y’s from the rectangles in the respective vectors.
  • Initialize a variable, say maxRectangles as 0 that stores the maximum overlapping rectangles.
  • Traverse the vector X[] and for each coordinate X[i], traverse the vector Y[] and find the number of overlapping rectangles with X[i] and after this step, update the value of maxRectangles to a maximum of maxRectangles and count obtained for the current iteration.
  • After completing the above steps, print the value of maxRectangles as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum number
// of overlapping rectangles
void maxOverlappingRectangles(
    int x1[], int y1[], int x2[],
    int y2[], int N)
{
    // Stores the maximum count of
    // overlapping rectangles
    int max_rectangles = 0;
 
    // Stores the X and Y coordinates
    vector<int> X, Y;
 
    for (int i = 0; i < N; i++) {
        X.push_back(x1[i]);
        X.push_back(x2[i] - 1);
        Y.push_back(y1[i]);
        Y.push_back(y2[i] - 1);
    }
 
    // Iterate over all pairs of Xs and Ys
    for (int i = 0; i < X.size(); i++) {
 
        for (int j = 0; j < Y.size(); j++) {
 
            // Store the count for the
            // current X and Y
            int cnt = 0;
            for (int k = 0; k < N; k++) {
 
                if (X[i] >= x1[k]
                    && X[i] + 1 <= x2[k]
                    && Y[j] >= y1[k]
                    && Y[j] + 1 <= y2[k]) {
                    cnt++;
                }
            }
 
            // Update the maximum count of
            // rectangles
            max_rectangles = max(
                max_rectangles, cnt);
        }
    }
 
    // Returns the total count
    cout << max_rectangles;
}
 
// Driver Code
int main()
{
    int x1[] = { 0, 50 };
    int y1[] = { 0, 50 };
    int x2[] = { 100, 60 };
    int y2[] = { 100, 60 };
    int N = sizeof(x1) / sizeof(x1[0]);
 
    maxOverlappingRectangles(
        x1, y1, x2, y2, N);
 
    return 0;
}

Java




// java program for the above approach
import java.util.*;
class GFG
{
 
  // Function to find the maximum number
  // of overlapping rectangles
  static void maxOverlappingRectangles(int[] x1, int[] y1,
                                       int[] x2, int[] y2,
                                       int N)
  {
 
    // Stores the maximum count of
    // overlapping rectangles
    int max_rectangles = 0;
 
    // Stores the X and Y coordinates
    Vector<Integer> X = new Vector<>();
    Vector<Integer> Y = new Vector<>();
 
    for (int i = 0; i < N; i++) {
      X.add(x1[i]);
      X.add(x2[i] - 1);
      Y.add(y1[i]);
      Y.add(y2[i] - 1);
    }
 
    // Iterate over all pairs of Xs and Ys
    for (int i = 0; i < X.size(); i++) {
 
      for (int j = 0; j < Y.size(); j++) {
 
        // Store the count for the
        // current X and Y
        int cnt = 0;
        for (int k = 0; k < N; k++) {
 
          if (X.get(i)>= x1[k] && X.get(i) + 1 <= x2[k]
              && Y.get(j) >= y1[k]
              && Y.get(j) + 1 <= y2[k]) {
            cnt++;
          }
        }
 
        // Update the maximum count of
        // rectangles
        max_rectangles
          = Math.max(max_rectangles, cnt);
      }
    }
 
    // Returns the total count
    System.out.println(max_rectangles);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
    int[] x1 = { 0, 50 };
    int[] y1 = { 0, 50 };
    int[] x2 = { 100, 60 };
    int[] y2 = { 100, 60 };
    int N = x1.length;
 
    maxOverlappingRectangles(x1, y1, x2, y2, N);
  }
}
 
// This code is contributed by amreshkumar3.

Python3




# Python3 program for the above approach
 
# Function to find the maximum number
# of overlapping rectangles
def maxOverlappingRectangles(x1, y1, x2, y2, N):
 
    # Stores the maximum count of
    # overlapping rectangles
    max_rectangles = 0
 
    # Stores the X and Y coordinates
    X = []
    Y = []
 
    for i in range(0, N):
        X.append(x1[i])
        X.append(x2[i] - 1)
        Y.append(y1[i])
        Y.append(y2[i] - 1)
 
        # Iterate over all pairs of Xs and Ys
    for i in range(0, len(X)):
        for j in range(0, len(Y)):
 
           # Store the count for the
           # current X and Y
            cnt = 0
            for k in range(0, N):
                if (X[i] >= x1[k] and X[i] + 1 <= x2[k] and Y[j] >= y1[k] and Y[j] + 1 <= y2[k]):
                    cnt += 1
 
            # Update the maximum count of
            # rectangles
            max_rectangles = max(max_rectangles, cnt)
 
        # Returns the total count
    print(max_rectangles)
 
 
# Driver Code
if __name__ == "__main__":
 
    x1 = [0, 50]
    y1 = [0, 50]
    x2 = [100, 60]
    y2 = [100, 60]
    N = len(x1)
 
    maxOverlappingRectangles(x1, y1, x2, y2, N)
 
    # This code is contributed by rakeshsahni

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
   
    // Function to find the maximum number
    // of overlapping rectangles
    static void maxOverlappingRectangles(int[] x1, int[] y1,
                                         int[] x2, int[] y2,
                                         int N)
    {
        // Stores the maximum count of
        // overlapping rectangles
        int max_rectangles = 0;
 
        // Stores the X and Y coordinates
        List<int> X = new List<int>();
        List<int> Y = new List<int>();
 
        for (int i = 0; i < N; i++) {
            X.Add(x1[i]);
            X.Add(x2[i] - 1);
            Y.Add(y1[i]);
            Y.Add(y2[i] - 1);
        }
 
        // Iterate over all pairs of Xs and Ys
        for (int i = 0; i < X.Count; i++) {
 
            for (int j = 0; j < Y.Count; j++) {
 
                // Store the count for the
                // current X and Y
                int cnt = 0;
                for (int k = 0; k < N; k++) {
 
                    if (X[i] >= x1[k] && X[i] + 1 <= x2[k]
                        && Y[j] >= y1[k]
                        && Y[j] + 1 <= y2[k]) {
                        cnt++;
                    }
                }
 
                // Update the maximum count of
                // rectangles
                max_rectangles
                    = Math.Max(max_rectangles, cnt);
            }
        }
 
        // Returns the total count
        Console.WriteLine(max_rectangles);
    }
 
    // Driver Code
    public static void Main()
    {
        int[] x1 = { 0, 50 };
        int[] y1 = { 0, 50 };
        int[] x2 = { 100, 60 };
        int[] y2 = { 100, 60 };
        int N = x1.Length;
 
        maxOverlappingRectangles(x1, y1, x2, y2, N);
    }
}
 
// This code is contributed by ukasp.

Javascript




<script>
        // JavaScript Program to implement
        // the above approach
 
        // Function to find the maximum number
        // of overlapping rectangles
        function maxOverlappingRectangles(
            x1, y1, x2,
            y2, N)
        {
            // Stores the maximum count of
            // overlapping rectangles
            let max_rectangles = 0;
 
            // Stores the X and Y coordinates
            let X = [], Y = [];
 
            for (let i = 0; i < N; i++) {
                X.push(x1[i]);
                X.push(x2[i] - 1);
                Y.push(y1[i]);
                Y.push(y2[i] - 1);
            }
 
            // Iterate over all pairs of Xs and Ys
            for (let i = 0; i < X.length; i++) {
 
                for (let j = 0; j < Y.length; j++) {
 
                    // Store the count for the
                    // current X and Y
                    let cnt = 0;
                    for (let k = 0; k < N; k++) {
 
                        if (X[i] >= x1[k]
                            && X[i] + 1 <= x2[k]
                            && Y[j] >= y1[k]
                            && Y[j] + 1 <= y2[k]) {
                            cnt++;
                        }
                    }
 
                    // Update the maximum count of
                    // rectangles
                    max_rectangles = Math.max(
                        max_rectangles, cnt);
                }
            }
 
            // Returns the total count
            document.write(max_rectangles);
        }
 
        // Driver Code
        let x1 = [0, 50];
        let y1 = [0, 50];
        let x2 = [100, 60];
        let y2 = [100, 60];
        let N = x1.length;
 
        maxOverlappingRectangles(
            x1, y1, x2, y2, N);
 
// This code is contributed by Potta Lokesh
    </script>
Output: 
2

 

Time Complexity: O(N3
Auxiliary Space: O(N)
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :