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.
Time Complexity of above code is O(1) as the code doesn’t have any loop or recursion.
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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Maximum number of operations required such that no pairs from a Matrix overlap
- Find side of Square which makes minimal area to fit two identical rectangles inside it
- Total area of two overlapping rectangles
- Intersecting rectangle when bottom-left and top-right corners of two rectangles are given
- Minimum area of square holding two identical rectangles
- Find all rectangles filled with 0
- Find the number of rectangles of size 2*1 which can be placed inside a rectangle of size n*m
- Find the minimum number of rectangles left after inserting one into another
- Create a matrix with alternating rectangles of O and X
- Number of unique rectangles formed using N unit squares
- Number of rectangles in N*M grid
- Sum of Areas of Rectangles possible for an array
- Number of rectangles in a circle of radius R
- Smallest square formed with given rectangles
- Check if it is possible to rearrange rectangles in a non-ascending order of breadths
- Count the number of rectangles such that ratio of sides lies in the range [a,b]
- Maximum given sized rectangles that can be cut out of a sheet of paper
- Largest subset of rectangles such that no rectangle fit in any other rectangle
- Count of distinct rectangles inscribed in an equilateral triangle
- Count Distinct Rectangles in N*N Chessboard