Problem
You are given given a list of rectangles represented by min and max x- and y-coordinates. Compute whether or not a pair of rectangles overlap each other. If one rectangle completely covers another, it is considered overlapping.
Examples
Example 1
|
|
Solution
Method 1 - Check if 2 Rectangles overlap in pairs
We have already seen Rectangle Overlap. We can reuse that solution and solve this problem.
To determine if any pair of rectangles overlap, we need to check if there’s any intersecting region between each pair of rectangles:
- Extract the coordinates of two rectangles.
- Check if one rectangle is completely to the left, right, above, or below the other.
- If none of these conditions are met, then the rectangles overlap.
Approach
- Extract Rectangle Edges: Identify the coordinates of the bottom-right corner using the top-left corner and dimensions.
- Check Overlap: Two rectangles do not overlap if one is completely to the left, right, above, or below the other.
- Compare All Pairs: Check all pairs of rectangles in the list to see if any pair overlaps.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
wheren
is the number of rectangles, since every pair of rectangles needs to be checked. - 🧺 Space complexity:
O(1)
as no additional data structures are needed except a few variables.