Find if two rectangles overlap - GeeksforGeeks

26 Oct, 2021
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.
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++
Java
Python3
C#
Javascript
// 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)// overlapbool doOverlap(Point l1, Point r1, Point l2, Point r2){     // To check if either rectangle is actually a line    // For example :  l1 ={-1,0}  r1={1,1}  l2={0,-1}    // r2={0,1}     if (l1.x == r1.x || l1.y == r1.y || l2.x == r2.x        || l2.y == r2.y) {        // the line cannot have positive overlap        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 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) {                    // To check if either rectangle is actually a line          // For example :  l1 ={-1,0}  r1={1,1}  l2={0,-1}  r2={0,1}              if (l1.x == r1.x || l1.y == r1.y || l2.x == r2.x || l2.y == r2.y)            {                    // the line cannot have positive overlap                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
# Python program to check if rectangles overlapclass Point:    def __init__(self, x, y):        self.x = x        self.y = y # Returns true if two rectangles(l1, r1)# and (l2, r2) overlapdef doOverlap(l1, r1, l2, r2):         # To check if either rectangle is actually a line      # For example  :  l1 ={-1,0}  r1={1,1}  l2={0,-1}  r2={0,1}           if (l1.x == r1.x or l1.y == r1.y or l2.x == r2.x or l2.y == r2.y):        # the line cannot have positive overlap        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 Codeif __name__ == "__main__":    l1 = Point(0, 10)    r1 = Point(10, 0)    l2 = Point(5, 5)    r2 = Point(15, 0)     if(doOverlap(l1, r1, l2, r2)):        print("Rectangles Overlap")    else:        print("Rectangles Don't Overlap") # This code is contributed by Vivek Kumar Singh
// C# program to check if rectangles overlapusing 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 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
<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) {         // To check if either rectangle is actually a line        // For example : l1 ={-1,0} r1={1,1} l2={0,-1} r2={0,1}         if (l1.x == r1.x || l1.y == r1.y ||        l2.x == r2.x || l2.y == r2.y) {            // the line cannot have positive overlap            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>
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)
YouTubeGeeksforGeeks507K subscribersFind if two rectangles overlap | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:18•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=wx0nyomRS_U" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is compiled by Aman Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
princiraj1992
Rajput-Ji
Vivekkumar Singh
shivamsingh49
rahulagarwal14
umadevi9616
nitishgautam1223
deepakkumar144
anupriya12
vaibhavilohani21
singhpraduman451
subhammahato348
Amazon
Expedia
Goldman Sachs
Microsoft
OATS Systems
square-rectangle
Geometric
Mathematical
Amazon
Microsoft
Goldman Sachs
OATS Systems
Expedia
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Optimum location of point to minimize total distance
Check whether a given point lies inside a triangle or not
Given n line segments, find if any two segments intersect
Polygon Clipping | Sutherland–Hodgman Algorithm
Program for Point of Intersection of Two Lines
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7