Perfect Rectangle - Problem

Given an array rectangles where rectangles[i] = [xi, yi, ai, bi] represents an axis-aligned rectangle. The bottom-left point of the rectangle is (xi, yi) and the top-right point is (ai, bi).

Return true if all the rectangles together form an exact cover of a rectangular region, meaning:

  • No gaps between rectangles
  • No overlapping areas
  • The combined shape is a perfect rectangle

Input & Output

Example 1 — Perfect Rectangle
$ Input: rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]
Output: true
💡 Note: The rectangles form a perfect 3×3 rectangle from (1,1) to (4,4) with no gaps or overlaps. Total area matches: 5 rectangles with areas 4+1+2+1+1 = 9, bounding rectangle area = 3×3 = 9.
Example 2 — Gap Exists
$ Input: rectangles = [[1,1,2,3],[1,3,2,4],[3,1,4,2]]
Output: false
💡 Note: There's a gap in the coverage. The rectangles don't form a complete rectangular region - missing area between coordinates (2,1) and (3,4).
Example 3 — Single Rectangle
$ Input: rectangles = [[0,0,4,1]]
Output: true
💡 Note: A single rectangle is always a perfect rectangle cover of itself. Area = 4×1 = 4, exactly matches bounding rectangle.

Constraints

  • 1 ≤ rectangles.length ≤ 2 × 104
  • rectangles[i].length == 4
  • -105 ≤ xi, yi, ai, bi ≤ 105
  • xi < ai and yi < bi

Visualization

Tap to expand
Perfect Rectangle - Corner Point Analysis INPUT R1 R2 R3 R4 R5 1 2 3 4 1 2 3 4 rectangles = [ [1,1,3,3], [3,1,4,2], [3,2,4,4], [1,3,2,4], [2,3,3,4] ] 5 rectangles total ALGORITHM STEPS 1 Track All Corners Store each corner with XOR to detect overlaps 2 Count Corner Occurrences Odd count = bounding rect Even count = internal 3 Verify 4 Corners Only Exactly 4 odd corners must form bounding box 4 Check Area Match Sum of all rect areas = bounding rect area Red=Odd, Gray=Even FINAL RESULT Perfect Cover - OK Verification: [OK] Exactly 4 odd corners [OK] Corners at (1,1)(4,1)(1,4)(4,4) [OK] Area: 4+2+2+1+1 = 9 = 3x3 Output: true Key Insight: A perfect rectangle cover has exactly 4 corners appearing an odd number of times (the bounding box corners). All internal corners appear an even number of times (2 or 4) as they are shared between adjacent rectangles. TutorialsPoint - Perfect Rectangle | Corner Point Analysis Approach
Asked in
Google 35 Facebook 28 Amazon 22 Microsoft 18
89.0K Views
Medium Frequency
~35 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen