Overlapping Rectangles || Expedia
2207

Question:

Given two rectangles, find if the given two rectangles overlap or not. A rectangle is denoted by providing the x and y coordinates of two points: the left top corner and the right bottom corner of the rectangle. Two rectangles sharing a side are considered overlapping. (L1 and R1 are the extreme points of the first rectangle and L2 and R2 are the extreme points of the second rectangle).

Note: It may be assumed that the rectangles are parallel to the coordinate axis.

Approach O(1) time :

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.

Instead of checking for any of the point of the one rectangle lies inside other rectangle which can be complex, we observe 2 key points :

Two rectangles do not overlap if one of the following conditions is true.

  • One rectangle is above top edge of other rectangle.
  • One rectangle is on left side of left edge of other rectangle.

If any of the 2 condition is true then that means the rectangles do not overlap else they do

Non Overlapping Conditions

image

image

image

C++ :

    int doOverlap(int L1[], int R1[], int L2[], int R2[]) {
        
        // left side
        if(R1[0]<L2[0] || R2[0]<L1[0]) return 0;
        
        // up side
        if(L2[1]<R1[1] || L1[1]<R2[1]) return 0;
        
        else return 1;
    }

Python

    def doOverlap(self, L1, R1, L2, R2):
        
        # If one rectangle is on left side of other
        if L1[0] >R2[0] or L2[0] > R1[0]:
            return 0
    
        # If one rectangle is above other
        if L1[1] < R2[1] or L2[1] <R1[1]:
            return 0

        return 1
Comments (1)