Overlapping Rectangles || Expedia

Difficulty: EASYCategory: InterviewExperienceFrequency: 1Asked On 2021-08-30Added By Anonymous
Source: Link
Expedia | Coding Question

## Question:\n*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).*\n\nNote: It may be assumed that the rectangles are parallel to the coordinate axis.\n\n## Approach O(1) time :\n*Note that a rectangle can be represented by two coordinates, top left and bottom right. So mainly we are given following four coordinates*. \nl1: Top Left coordinate of first rectangle. \nr1: Bottom Right coordinate of first rectangle. \nl2: Top Left coordinate of second rectangle. \nr2: Bottom Right coordinate of second rectangle.\n\nInstead of checking for any of the point of the one rectangle lies inside other rectangle which can be complex, we observe 2 key points :\n\nTwo rectangles do not overlap if one of the following conditions is true. \n* One rectangle is above top edge of other rectangle. \n* One rectangle is on left side of left edge of other rectangle.\n\n### If any of the 2 condition is true then that means the rectangles do not overlap else they do\n\n# Non Overlapping Conditions\n

\n\n

\n\n

\n\n# C++ :\n\n int doOverlap(int L1[], int R1[], int L2[], int R2[]) {\n \n // left side\n if(R1[0]<L2[0] || R2[0]<L1[0]) return 0;\n \n // up side\n if(L2[1]<R1[1] || L1[1]<R2[1]) return 0;\n \n else return 1;\n }\n\n\n# Python\n\n def doOverlap(self, L1, R1, L2, R2):\n \n # If one rectangle is on left side of other\n if L1[0] >R2[0] or L2[0] > R1[0]:\n return 0\n \n # If one rectangle is above other\n if L1[1] < R2[1] or L2[1] <R1[1]:\n return 0\n\n return 1\n\n
Comments