You are given a list of axis-aligned rectangles. Each one is [x1, y1, x2, y2], where (x1, y1) is its bottom-left corner and (x2, y2) its top-right corner.
Return true if the rectangles fit together into one larger rectangle exactly: no gaps inside it and no two rectangles sharing any area. Touching along edges or at corners is fine.
Example 1
Input: rectangles = [[0,0,2,1], [2,0,3,2], [0,1,2,2]] Output: true Why: the three pieces tile the box from (0,0) to (3,2)
2 more examples and the constraints
Example 2
Input: rectangles = [[0,0,1,2], [2,0,3,1], [2,1,3,2]] Output: false Why: nothing covers the strip between x = 1 and x = 2
Example 3
Input: rectangles = [[0,0,2,2], [1,1,3,3], [0,2,1,3], [2,0,3,1]] Output: false Why: the first two share the square (1,1) to (2,2)
Constraints
- 1 ≤ rectangles.length ≤ 20,000
- rectangles[i] has 4 integers
- −100,000 ≤ x1 < x2 ≤ 100,000
- −100,000 ≤ y1 < y2 ≤ 100,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Area plus pairwise overlapO(n²)
- Area plus corner parityO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Checks for 20,000 rectangles | Verdict |
|---|---|---|---|
| Pairwise overlap | O(n²) | Too slow at the limit | |
| Corner parity | O(n) | Best; one pass |
n = number of rectangles.
Edge cases to test
- One rectangle. It covers itself exactly: true.
- A duplicate. The same rectangle twice cancels all its corners and doubles the area: false.
- Only touching at a corner. [[0,0,1,1], [1,1,2,2]] leaves two empty squares in the box: false.
- Large coordinates. The box can be 200,000 × 200,000, so areas need 64-bit integers.
Common mistakes
- Checking only the area, which an overlap plus a gap of the same size can fool.
- Checking only the corners, which stacked pieces can fool.
- Storing areas in 32-bit integers; a single rectangle can have area 4 × 10¹⁰.
How to talk through it
- 1Clarify. Do pieces touching at an edge count as fine? Can the input contain the same rectangle twice?
- 2Name the two conditions. No gaps and no overlaps; with no overlaps, no gaps is the same as the areas adding up.
- 3Give the pair check. Area plus testing every pair for overlap works but is O(n²).
- 4Count corners. In a tiling, inner corners come in pairs or fours; only the four box corners are odd. Toggle corners in a set.
- 5Test out loud. Run Example 1, a duplicate rectangle, and the stacked case that fools corners alone.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?