Rectangle Overlap
Problem
Each rectangle is given as [x1, y1, x2, y2]. Return true if they overlap with positive area, otherwise false.
rec1 = [0,0,2,2], rec2 = [1,1,3,3]truedef isRectangleOverlap(rec1, rec2):
return (rec1[0] < rec2[2] and rec2[0] < rec1[2] and
rec1[1] < rec2[3] and rec2[1] < rec1[3])
function isRectangleOverlap(rec1, rec2) {
return rec1[0] < rec2[2] && rec2[0] < rec1[2] &&
rec1[1] < rec2[3] && rec2[1] < rec1[3];
}
class Solution {
public boolean isRectangleOverlap(int[] rec1, int[] rec2) {
return rec1[0] < rec2[2] && rec2[0] < rec1[2]
&& rec1[1] < rec2[3] && rec2[1] < rec1[3];
}
}
class Solution {
public:
bool isRectangleOverlap(vector<int>& rec1, vector<int>& rec2) {
return rec1[0] < rec2[2] && rec2[0] < rec1[2]
&& rec1[1] < rec2[3] && rec2[1] < rec1[3];
}
};
Explanation
Two axis-aligned rectangles overlap with real area only if they overlap on both the horizontal (x) axis and the vertical (y) axis at the same time. If they miss on either axis, there is a gap and no overlap.
Think of each axis separately. On the x-axis, rectangle 1 spans [rec1[0], rec1[2]] and rectangle 2 spans [rec2[0], rec2[2]]. They overlap when each one starts before the other ends: rec1[0] < rec2[2] and rec2[0] < rec1[2]. The same logic applies to the y-axis using indices 1 and 3.
Using strict < (not ≤) matters: if they only touch along an edge, the shared region has zero area, which doesn't count as overlapping.
So the whole answer is just the four conditions joined with and — true only when both projections overlap.
Example: rec1=[0,0,2,2], rec2=[1,1,3,3]. On x: 0<3 and 1<2 hold; on y: 0<3 and 1<2 hold. All true, so they overlap (in the square from (1,1) to (2,2)) → true.