Rectangle Overlap
A rectangle is represented as a list[x1, y1, x2, y2]
, where (x1, y1)
are the coordinates of its bottom-left corner, and(x2, y2)
are the coordinates of its top-right corner.
Two rectangles overlap if the area of their intersection is positive. To be clear, two rectangles that only touch at the corner or edges do not overlap.
Given two (axis-aligned) rectangles, return whether they overlap.
Example 1:
Example 2:
Notes:
Both rectangles
rec1
andrec2
are lists of 4 integers.All coordinates in rectangles will be between
-10^9
and10^9
.
Analysis
Check Position
The answer for whether they don't overlap is LEFT OR RIGHT OR UP OR DOWN
, where OR
is the logical OR, and LEFT
is a boolean that represents whether rec1
is to the left of rec2
. The answer for whether they do overlap is the negation of this.
The condition "rec1
is to the left of rec2
" is rec1[2] <= rec2[0]
, that is the right-most x-coordinate of rec1
is left of the left-most x-coordinate of rec2
.
Check Area
The overlapping area is positive: Thus, we can reduce the problem to the one-dimensional problem of determining whether two line segments overlap.
Solution
Check Position
Check Area
Time and Space Complexity: O(1).
A rectangle with zero area inside the other rectangle would be a problem for this solution though. Need to clarify to exclude this case.
Last updated