The Wayback Machine - https://web.archive.org/web/20240928070511/https://www.geeksforgeeks.org/find-two-rectangles-overlap/
Open In App

Find if two rectangles overlap

Last Updated : 07 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two rectangles, find if the given two rectangles overlap or not.
Note that a rectangle can be represented by two coordinates, top left and bottom right. So mainly we are given following four coordinates. 
l1: Top Left coordinate of first rectangle. 
r1: Bottom Right coordinate of first rectangle. 
l2: Top Left coordinate of second rectangle. 
r2: Bottom Right coordinate of second rectangle.

rectanglesOverlap


We need to write a function bool doOverlap(l1, r1, l2, r2) that returns true if the two given rectangles overlap. 


Note : It may be assumed that the rectangles are parallel to the coordinate axis.
One solution is to one by one pick all points of one rectangle and see if the point lies inside the other rectangle or not. This can be done using the algorithm discussed here. 
Following is a simpler approach. Two rectangles do not overlap if one of the following conditions is true. 
1) One rectangle is above top edge of other rectangle. 
2) One rectangle is on left side of left edge of other rectangle.
We need to check above cases to find out if given rectangles overlap or not. Following is the implementation of the above approach. 

C++
// CPP program for the above approach
#include <bits/stdc++.h>

struct Point {
    int x, y;
};

// Returns true if two rectangles (l1, r1) and (l2, r2)
// overlap
bool doOverlap(Point l1, Point r1, Point l2, Point r2)
{
   if (l1.x > r2.x || l2.x > r1.x)
        return false;

    // If one rectangle is above the other
    if (r1.y > l2.y || r2.y > l1.y)
        return false;

    return true;
}

/* Driver program to test above function */
int main()
{
    Point l1 = { 0, 10 }, r1 = { 10, 0 };
    Point l2 = { 5, 5 }, r2 = { 15, 0 };
    if (doOverlap(l1, r1, l2, r2))
        printf("Rectangles Overlap");
    else
        printf("Rectangles Don't Overlap");
    return 0;
}
Java
public class RectangleOverlap {

    static class Point {
        int x, y;
        
        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }

    // Returns true if two rectangles (l1, r1) and (l2, r2) overlap
    static boolean doOverlap(Point l1, Point r1, Point l2, Point r2) {
        // If one rectangle is to the left of the other
        if (l1.x > r2.x || l2.x > r1.x)
            return false;

        // If one rectangle is above the other
        if (r1.y > l2.y || r2.y > l1.y)
            return false;

        return true;
    }

    public static void main(String[] args) {
        Point l1 = new Point(0, 10);
        Point r1 = new Point(10, 0);
        Point l2 = new Point(5, 5);
        Point r2 = new Point(15, 0);

        if (doOverlap(l1, r1, l2, r2))
            System.out.println("Rectangles Overlap");
        else
            System.out.println("Rectangles Don't Overlap");
    }
}
Python
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

def do_overlap(l1, r1, l2, r2):
    # If one rectangle is to the left of the other
    if l1.x > r2.x or l2.x > r1.x:
        return False

    # If one rectangle is above the other
    if r1.y > l2.y or r2.y > l1.y:
        return False

    return True

# Driver code
if __name__ == "__main__":
    l1 = Point(0, 10)
    r1 = Point(10, 0)
    l2 = Point(5, 5)
    r2 = Point(15, 0)

    if do_overlap(l1, r1, l2, r2):
        print("Rectangles Overlap")
    else:
        print("Rectangles Don't Overlap")
C#
using System;

class RectangleOverlap
{
    public struct Point
    {
        public int x, y;
        public Point(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

    // Returns true if two rectangles (l1, r1) and (l2, r2) overlap
    static bool DoOverlap(Point l1, Point r1, Point l2, Point r2)
    {
        // If one rectangle is to the left of the other
        if (l1.x > r2.x || l2.x > r1.x)
            return false;

        // If one rectangle is above the other
        if (r1.y > l2.y || r2.y > l1.y)
            return false;

        return true;
    }

    static void Main()
    {
        Point l1 = new Point(0, 10);
        Point r1 = new Point(10, 0);
        Point l2 = new Point(5, 5);
        Point r2 = new Point(15, 0);

        if (DoOverlap(l1, r1, l2, r2))
            Console.WriteLine("Rectangles Overlap");
        else
            Console.WriteLine("Rectangles Don't Overlap");
    }
}
JavaScript
class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}

// Returns true if two rectangles (l1, r1) and (l2, r2) overlap
function doOverlap(l1, r1, l2, r2) {
    // If one rectangle is to the left of the other
    if (l1.x > r2.x || l2.x > r1.x)
        return false;

    // If one rectangle is above the other
    if (r1.y > l2.y || r2.y > l1.y)
        return false;

    return true;
}

// Driver code
const l1 = new Point(0, 10);
const r1 = new Point(10, 0);
const l2 = new Point(5, 5);
const r2 = new Point(15, 0);

if (doOverlap(l1, r1, l2, r2)) {
    console.log("Rectangles Overlap");
} else {
    console.log("Rectangles Don't Overlap");
}

Output
Rectangles Overlap

The Time Complexity of the above code is O(1) as the code doesn’t have any loop or recursion. 

Auxiliary Space: O(1)




Previous Article
Next Article

Similar Reads

Maximum rods to put horizontally such that no two rods overlap on X coordinate
Given two arrays X[] and H[] of size N, where X[i] denotes the X-coordinate of the ith vertical rod and H[i] denotes the height of that rod, and also given that an ith rod can also be put horizontally, by either placing the rod on the segment [X[i]-H[i], X[i]] or [X[i], X[i]+H[i]] on the X coordinate, the task is to find the maximum number of rods
7 min read
Find the point where maximum intervals overlap
Consider a big party where a log register for guest's entry and exit times is maintained. Find the time at which there are maximum guests in the party. Note that entries in register are not in any order.Example : Input: arrl[] = {1, 2, 9, 5, 5} exit[] = {4, 5, 12, 9, 12} First guest in array arrives at 1 and leaves at 4, second guest arrives at 2 a
13 min read
Find side of Square which makes minimal area to fit two identical rectangles inside it
Given height H, and width W, of a rectangle, the task is to find the side of a square of the minimum area in which two rectangles fit completely. Note: Two rectangles can touch each other by side or corner.Rectangles cannot intersect each other.Rectangles can also touch the sides of the square but must be completely inside it.The Rectangles can be
12 min read
Maximum number of operations required such that no pairs from a Matrix overlap
Given an integer N followed by a matrix V[][] consisting of pairs {X, Y} in ascending order of X, the task is to for each pair given in ascending order of X, the following operations can be performed: Convert the pair {X, Y} to {X - Y, X}Convert the pair {X, Y} to {X, X+Y}Change the pair to {X, X} The task is to find the count of addition and subtr
6 min read
Minimum time at which at least K out of N circles expanding 1 unit per second overlap
Given N points on a 2D infinite plane, where each point represents the center of a circle initially having a radius of 0 which expands at a constant rate of 1 unit per second, the task is to find the minimum time at which at least K circles overlap at a point. Example: Input: points[] = {{8, 5}, {0, 4}, {3, 6}}, K = 3Output: 5 Explanation: Consider
15+ min read
Maximum prefix sum which is equal to suffix sum such that prefix and suffix do not overlap
Given an array arr[] of N Positive integers, the task is to find the largest prefix sum which is also the suffix sum and prefix and suffix do not overlap. Examples: Input: N = 5, arr = [1, 3, 2, 1, 4]Output: 4Explanation: consider prefix [1, 3] and suffix [4] which gives maximum prefix sum which is also suffix sum such that prefix and suffix do not
7 min read
Check if any K ranges overlap at any point
Given N ranges [L, R] and an integer K, the task is to check if there are any K ranges that overlap at any point. Examples: Input: ranges[][] = {{1, 3}, {2, 4}, {3, 4}, {7, 10}}, K = 3 Output: Yes 3 is a common point among the ranges {1, 3}, {2, 4} and {3, 4}. Input: ranges[][] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}, K = 2 Output: No Recommended: Pleas
13 min read
Maximum image overlap on given binary Matrices
Given two images represented as binary square matrices, matrix1[] and matrix2[] of size n x n, the task is to find the largest possible overlap of 1 in both matrices by translating one matrix over other any number of times to left, right, up, and/or down without any rotation. Note: Any 1-bit translated outside the matrix borders is erased. Examples
12 min read
Intersecting rectangle when bottom-left and top-right corners of two rectangles are given
Given coordinates of 4 points, bottom-left and top-right corners of two rectangles. The task is to find the coordinates of the intersecting rectangle formed by the given two rectangles. Examples: Input: rec1: bottom-left(0, 0), top-right(10, 8), rec2: bottom-left(2, 3), top-right(7, 9) Output: (2, 3) (7, 8) (2, 8) (7, 3) Input: rec1: bottom-left(0,
10 min read
Minimum area of square holding two identical rectangles
Given the length L and breadth B of two identical rectangles, the task is to find the minimum area of a square in which the two identical rectangles with dimensions L × B can be embedded.Examples: Input: L = 7, B = 4 Output: 64 Explanation: Two rectangles with sides 7 x 4 can fit into square with side 8. By placing two rectangles with side 4 upon e
4 min read
Perimeter of the Union of Two Rectangles
Given two arrays X[] and Y[], each of length 4, where (X[0], Y[0]) and (X[1], Y[1]) represents the bottom left and top right corners of one rectangle and (X[2], Y[2]) and (X[3], Y[3]) represents the bottom left and top right corners of the other rectangle, the task is to find the perimeter of the outer boundaries of the union of the two rectangles
7 min read
Total area of two overlapping rectangles
Given the coordinates of two rectangles in a 2D plane, the first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2) and the second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2). The task is to find the total area covered by the two rectangles. Examples: Input
7 min read
Find the number of rectangles of size 2*1 which can be placed inside a rectangle of size n*m
Given two integers n, m. Find the number of rectangles of size 2*1 that can be placed inside a rectangle of size n*m. Note: No two small rectangles overlap.Each small rectangle lies entirely inside the large rectangle. It is allowed to touch the edges of the large rectangle. Examples: Input : n = 3, m =3 Output : 4 Input : n = 2, m = 4 Output : 4 A
6 min read
Find the minimum number of rectangles left after inserting one into another
Given width and height of N rectangles. The task is to find the minimum number of rectangles left after inserting one into another. Note : If W1 < W2 and H1 < H2 then rectangle 1 fits inside rectangle 2.The smallest rectangle can insert in the second smallest, and this rectangle can insert in the next one and so forth. Examples: Input : arr[]
9 min read
Find the number of corner rectangles that can be formed from given Matrix
Given a binary matrix mat[][] of dimensions N*M, the task is to find the number of corner rectangles that can be formed. A corner rectangle is defined as the submatrix having 1s on the corners of it and each 1s must belong to a unique cell in that submatrix. Examples: Input: mat[][] = {{1, 0, 1}, {0, 0, 0}, {1, 0, 1}}Output: 1Explanation:There exis
7 min read
Find all rectangles filled with 0
We have one 2D array, filled with zeros and ones. We have to find the starting point and ending point of all rectangles filled with 0. It is given that rectangles are separated and do not touch each other however they can touch the boundary of the array. A rectangle might contain only one element. Examples: input = [ [1, 1, 1, 1, 1, 1, 1], [1, 1, 1
12 min read
Find number of rectangles that can be formed from a given set of coordinates
Given an array arr[][] consisting of pair of integers denoting coordinates. The task is to count the total number of rectangles that can be formed using given coordinates. Examples: Input: arr[][] = {{0, 0}, {0, 1}, {1, 0}, {1, 1}, {2, 0}, {2, 1}, {11, 11}}Output: 3Explanation: Following are the rectangles formed using given coordinates. First Rect
6 min read
Create a matrix with alternating rectangles of O and X
Write a code which inputs two numbers m and n and creates a matrix of size m x n (m rows and n columns) in which every elements is either X or 0. The Xs and 0s must be filled alternatively, the matrix should have outermost rectangle of Xs, then a rectangle of 0s, then a rectangle of Xs, and so on. Examples: Input: m = 3, n = 3 Output: Following mat
15 min read
Sum of Areas of Rectangles possible for an array
Given an array, the task is to compute the sum of all possible maximum area rectangles which can be formed from the array elements. Also, you can reduce the elements of the array by at most 1. Examples: Input: a = {10, 10, 10, 10, 11, 10, 11, 10} Output: 210 Explanation: We can form two rectangles one square (10 * 10) and one (11 * 10). Hence, tota
13 min read
Smallest square formed with given rectangles
Given a rectangle of length l and breadth b, we need to find the area of the smallest square which can be formed with the rectangles of these given dimensions. Examples: Input : 1 2 Output : 4 We can form a 2 x 2 square using two rectangles of size 1 x 2. Input : 7 10 Output :4900 Let's say we want to make a square of side length a from rectangles
6 min read
Check if it is possible to rearrange rectangles in a non-ascending order of breadths
Given n number of rectangles with it's L-length and B-Breadth. We can turn any rectangle by 90 degrees. In other words, after turning them, the breadth will become length and length will be breadth. The task is to check if there is a way to make the rectangles go in order of non-ascending breadth. That is, a breadth of every rectangle has to be not
7 min read
Count the number of rectangles such that ratio of sides lies in the range [a,b]
Given the length and breadth of N rectangles and a range i.e. [a, b], the task is to count the number of rectangles whose sides(larger/smaller) ratio is in the range [a, b]. Examples: Input: {{165, 100}, {180, 100}, {100, 170}}, a = 1.6, b = 1.7 Output: 2 165/100 = 1.65 170/100 = 1.7 Input: {{10, 12}, {26, 19}}, a = 0.8, b = 1.2 Output: 1 Approach:
5 min read
Maximum given sized rectangles that can be cut out of a sheet of paper
Given the length L and breadth B of a sheet of paper, the task is to find the maximum number of rectangles with given length l and breadth b that can be cut from this sheet of paper.Examples: Input: L = 5, B = 2, l = 14, b = 3 Output: 0 The sheet is smaller than the required rectangle. So, no rectangle of the given dimension can be cut from the she
6 min read
Largest subset of rectangles such that no rectangle fit in any other rectangle
Given height and width of N rectangles. The task is to find the size of the largest subset such that no pair of rectangles fit within each other. Note that if H1 ? H2 and W1 ? W2 then rectangle 1 fits inside rectangle 2. Examples: Input: arr[] = {{1, 3}, {2, 2}, {1, 3}} Output: 2 The required sub-set is {{1, 3}, {2, 2}} {1, 3} is included only once
15 min read
Count of distinct rectangles inscribed in an equilateral triangle
Given an equilateral triangle made of dots (.) joined together to form triangle and an integer n which represents the length of the sides of the triangle. The task is to count the number of rectangles that can be inscribed in the given triangle such that: Horizontal edges must be parallel to the base of the given triangle.Rectangle must only be for
11 min read
Count Distinct Rectangles in N*N Chessboard
Given a N x N Chessboard. The task is to count distinct rectangles from the chessboard. For example, if the input is 8 then the output should be 36.Examples: Input: N = 4 Output: 10 Input: N = 6 Output: 21 Approach: Suppose N = 8 i.e. 8 x 8 chessboard is given, So different rectangles that can be formed are: 1 x 1, 1 x 2, 1 x 3, 1 x 4, 1 x 5, 1 x 6
3 min read
Check if N rectangles of equal area can be formed from (4 * N) integers
Given an integer N and an array arr[] of size 4 * N, the task is to check whether N rectangles of equal area can be formed from this array if each element can be used only once. Examples: Input: arr[] = {1, 8, 2, 1, 2, 4, 4, 8}, N = 2 Output: Yes Two rectangles with sides (1, 8, 1, 8) and (2, 4, 2, 4) can be formed. Both of these rectangles have th
6 min read
Count of rectangles possible from N and M straight lines parallel to X and Y axis respectively
Given two integers N and M, where N straight lines are parallel to the X-axis and M straight lines are parallel to Y-axis, the task is to calculate the number of rectangles that can be formed by these lines. Examples: Input: N = 3, M = 6 Output: 45 Explanation: There are total 45 rectangles possible with 3 lines parallel to x axis and 6 lines paral
5 min read
Missing vertex among N axis-parallel rectangles
Given N axis-parallel rectangles in a 2-D Cartesian coordinate system and coordinates of 4N-1 vertices, the task is to find the single vertex missing. Examples: Input: N = 2, V[][] = {{1, 1}, {1, 2}, {4, 6}, {2, 1}, {9, 6}, {9, 3}, {4, 3}}Output: {2, 2} Explanation: The coordinates forming an axis parallel rectangle are {4, 6}, {9, 6}, {4, 3}, {9,
9 min read
Count of Rectangles with area K made up of only 1s from given Binary Arrays
Given two binary arrays A[] and B[], of length N and M respectively, the task is to find the number of rectangles of area K consisting of 1's in the matrix C[][] generated by multiplying the two arrays such that, C[i][j] = A[i] * B[j] (1< i < n, 1< j < m). Examples: Input: N= 3, M = 3, A[] = {1, 1, 0}, B[] = {0, 1, 1}, K = 2 Output: 4 E
11 min read