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

Find if two rectangles overlap

Last Updated : 06 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

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. 

Recommended Practice

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 rectangle has area 0, no overlap
    if (l1.x == r1.x || l1.y == r1.y || r2.x == l2.x || l2.y == r2.y)
        return false;
   
    // If one rectangle is on left side of other
    if (l1.x > r2.x || l2.x > r1.x)
        return false;
 
    // If one rectangle is above 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




// Java program to check if rectangles overlap  
class GFG {
 
   static class Point {
 
        int x, y;
    }
 
// Returns true if two rectangles (l1, r1) and (l2, r2) overlap
 static  boolean doOverlap(Point l1, Point r1, Point l2, Point r2) {
        // if rectangle has area 0, no overlap
        if (l1.x == r1.x || l1.y == r1.y || r2.x == l2.x || l2.y == r2.y)
            return false;
     
           // If one rectangle is on left side of other
        if (l1.x > r2.x || l2.x > r1.x) {
            return false;
        }
 
        // If one rectangle is above other
        if (r1.y > l2.y || r2.y > l1.y) {
            return false;
        }
 
        return true;
    }
 
    /* Driver program to test above function */
    public static void main(String[] args) {
        Point l1 = new Point(),r1 = new Point(),
                l2 = new Point(),r2 = new Point();
        l1.x=0;l1.y=10; r1.x=10;r1.y=0;
         l2.x=5;l2.y=5; r2.x=15;r2.y=0;
 
        if (doOverlap(l1, r1, l2, r2)) {
            System.out.println("Rectangles Overlap");
        } else {
            System.out.println("Rectangles Don't Overlap");
        }
    }
}
//this code contributed by PrinciRaj1992


Python3




# Python program to check if rectangles overlap
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
 
# Returns true if two rectangles(l1, r1)
# and (l2, r2) overlap
def do_overlap(l1, r1, l2, r2):
     
    # if rectangle has area 0, no overlap
    if l1.x == r1.x or l1.y == r1.y or r2.x == l2.x or l2.y == r2.y:
        return False
     
    # If one rectangle is on left side of other
    if l1.x > r2.x or l2.x > r1.x:
        return False
 
    # If one rectangle is above 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")
 
# This code is contributed by Vivek Kumar Singh


C#




// C# program to check if rectangles overlap
using System;
     
class GFG
{
    class Point
    {
        public int x, y;
    }
 
    // Returns true if two rectangles (l1, r1)
    // and (l2, r2) overlap
    static bool doOverlap(Point l1, Point r1,
                          Point l2, Point r2)
    {
        // if rectangle has area 0, no overlap
        if (l1.x == r1.x || l1.y == r1.y || r2.x == l2.x || l2.y == r2.y)
        {
            return false;
        }
       
        // If one rectangle is on left side of other
        if (l1.x > r2.x || l2.x > r1.x)
        {
            return false;
        }
 
        // If one rectangle is above other
        if (r1.y > l2.y || r2.y > l1.y)
        {
            return false;
        }
        return true;
    }
 
    // Driver Code
    public static void Main()
    {
        Point l1 = new Point(), r1 = new Point(),
                l2 = new Point(), r2 = new Point();
        l1.x = 0;l1.y = 10; r1.x = 10;r1.y = 0;
        l2.x = 5;l2.y = 5; r2.x = 15;r2.y = 0;
        if (doOverlap(l1, r1, l2, r2))
        {
            Console.WriteLine("Rectangles Overlap");
        } else
        {
            Console.WriteLine("Rectangles Don't Overlap");
        }
    }
}
 
// This code is contributed by
// Rajput-Ji


Javascript




<script>
 
// JavaScript program to check if rectangles overlap 
class Point {
 
            constructor(val) {
                this.x = val;
                this.y = val;
            }
        }
 
    // Returns true if two rectangles
    // (l1, r1) and (l2, r2) overlap
    function doOverlap( l1,  r1,  l2,  r2) {
 
        // if rectangle has area 0, no overlap
        if (l1.x == r1.x || l1.y == r1.y || r2.x == l2.x || l2.y == r2.y)
            return false;
     
        // If one rectangle is on left side of other
        if (l1.x > r2.x || l2.x > r1.x) {
            return false;
        }
 
        // If one rectangle is above other
        if (r1.y > l2.y || r2.y > l1.y) {
            return false;
        }
 
        return true;
    }
 
    /* Driver program to test above function */
     
        var l1 = new Point(), r1 = new Point(),
        l2 = new Point(), r2 = new Point();
        l1.x = 0;
        l1.y = 10;
        r1.x = 10;
        r1.y = 0;
        l2.x = 5;
        l2.y = 5;
        r2.x = 15;
        r2.y = 0;
 
        if (doOverlap(l1, r1, l2, r2)) {
            document.write("Rectangles Overlap");
        } else {
            document.write("Rectangles Don't Overlap");
        }
 
// This code contributed by umadevi9616
 
</script>


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)

This article is compiled by Aman Gupta.  



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
three90RightbarBannerImg