Problem Description
Given an array of axis-aligned rectangles, where each rectangle is represented by its bottom-left point (x, y) and top-right point (a, b), determine if all the rectangles together form an exact cover of a rectangular region with no overlaps and no gaps.
Key Insights
- Compute the overall bounding rectangle by taking the minimum x, minimum y, maximum a, and maximum b from all rectangles.
- Sum the areas of all given rectangles; this should equal the area of the overall bounding rectangle.
- Use a set to track all four corners of each rectangle. For each rectangle, add its four corners if they are seen for the first time and remove them if they appear again.
- At the end, the set should contain exactly the four corners of the overall bounding rectangle. Any extra points indicate either overlapping or gaps.
Space and Time Complexity
Time Complexity: O(n), where n is the number of rectangles, because we iterate through each rectangle exactly once. Space Complexity: O(n) in the worst-case scenario for storing corner points in the set.
Solution
The solution is based on two main observations. First, the total area of all small rectangles must equal the area of the overall bounding rectangle defined by the extreme coordinates. Second, by using a set to add and remove corner points of every rectangle, all internal points (which occur more than once) cancel out, leaving only the four corner points of the bounding rectangle. If the set does not exactly match these four corners, then the rectangles do not form a perfect cover.