Rectangle Overlap

Two rectangles overlap if one’s maximum x-coordinate is greater than the other’s minimum x-coordinate and the maximum y-coordinate is greater than the other’s minimum y-coordinate. It is also necessary to ensure the minimum x and y of one rectangle is less than the maximum x and y of the other.

Python solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
    def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
        # Check if the maximum x-coordinate of the two rectangles' left side is less than the minimum x-coordinate of their right side
        x_overlap = max(rec1[0], rec2[0]) < min(rec1[2], rec2[2])

        # Check if the maximum y-coordinate of the two rectangles' bottom side is less than the minimum y-coordinate of their top side
        y_overlap = max(rec1[1], rec2[1]) < min(rec1[3], rec2[3])

        # Return True if both x_overlap and y_overlap are True, else return False
        return x_overlap and y_overlap

In this function, max(rec1[0], rec2[0]) < min(rec1[2], rec2[2]) checks the x-coordinates, and max(rec1[1], rec2[1]) < min(rec1[3], rec2[3]) checks the y-coordinates.

This solution is efficient with a time complexity of O(1), as it performs a constant number of operations, and a space complexity of O(1), as it uses a constant amount of space.