Leetcode 836. Rectangle Overlap
You are given two axis-aligned rectangles rec1
and rec2
, represented as lists of 4 integers [x1, y1, x2, y2]
, where (x1, y1)
represents the bottom-left corner and (x2, y2)
represents the top-right corner of the rectangle. Write a function to determine if these two rectangles overlap.
Rectangles overlap when there is a non-empty rectangle that is covered by both rectangles.
Return true
if they overlap, otherwise return false
.
To determine if two rectangles overlap, we can use the principle that two rectangles do not overlap if one is entirely to the left, right, above, or below the other rectangle.
Given rec1 = [x1, y1, x2, y2]
and rec2 = [x1', y1', x2', y2']
:
rec1[2] <= rec2[0]
(right edge of Rec1 is to the left of the left edge of Rec2).rec1[0] >= rec2[2]
(left edge of Rec1 is to the right of the right edge of Rec2).rec1[1] >= rec2[3]
(bottom edge of Rec1 is above the top edge of Rec2).rec1[3] <= rec2[1]
(top edge of Rec1 is below the bottom edge of Rec2).If none of the above conditions are true, the rectangles must overlap.
#include <vector>
using namespace std;
class Solution {
public:
bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) {
// Check if one rectangle is to the left of the other
if (rec1[2] <= rec2[0] || rec2[2] <= rec1[0]) {
return false;
}
// Check if one rectangle is above the other
if (rec1[3] <= rec2[1] || rec2[3] <= rec1[1]) {
return false;
}
return true;
}
};
The time complexity of this solution is O(1)
because we are only performing a fixed number of comparison operations, regardless of the size or position of the rectangles. This makes the solution very efficient.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?