The rectangles fail to overlap only when one is completely left, right, above, or below the other; negate those separation cases.
Complexity
O(1) time and O(1) space.
Determine whether two axis-aligned rectangles overlap with positive area.
The rectangles fail to overlap only when one is completely left, right, above, or below the other; negate those separation cases.
O(1) time and O(1) space.
package main
func isRectangleOverlap(rec1 []int, rec2 []int) bool {
return rec1[0] < rec2[2] && rec2[0] < rec1[2] && rec1[1] < rec2[3] && rec2[1] < rec1[3]
}
class Solution:
def isRectangleOverlap(self, rec1: list[int], rec2: list[int]) -> bool:
return rec1[0] < rec2[2] and rec2[0] < rec1[2] and rec1[1] < rec2[3] and rec2[1] < rec1[3]
function isRectangleOverlap(rec1: number[], rec2: number[]): boolean {
return rec1[0] < rec2[2] && rec2[0] < rec1[2] && rec1[1] < rec2[3] && rec2[1] < rec1[3];
}