Rectangle Area II - Problem

You are given a 2D array of axis-aligned rectangles. Each rectangle[i] = [x₁, y₁, x₂, y₂] denotes the i-th rectangle where (x₁, y₁) are the coordinates of the bottom-left corner, and (x₂, y₂) are the coordinates of the top-right corner.

Calculate the total area covered by all rectangles in the plane. Any area covered by two or more rectangles should only be counted once.

Return the total area. Since the answer may be too large, return it modulo 10⁹ + 7.

Input & Output

Example 1 — Two Overlapping Rectangles
$ Input: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]
Output: 6
💡 Note: Three rectangles with some overlap. Rectangle 1: area 4, Rectangle 2: area 6, Rectangle 3: area 2. Total covered area after removing overlaps is 6.
Example 2 — Single Rectangle
$ Input: rectangles = [[0,0,1000000000,1000000000]]
Output: 49
💡 Note: Single large rectangle. Area = 10^18, which modulo 10^9+7 equals 49.
Example 3 — No Overlap
$ Input: rectangles = [[0,0,1,1],[2,2,3,3]]
Output: 2
💡 Note: Two rectangles with no overlap. Each has area 1, so total is 2.

Constraints

  • 1 ≤ rectangles.length ≤ 200
  • rectangles[i].length == 4
  • 0 ≤ xi1, yi1, xi2, yi2 ≤ 109
  • xi1 < xi2 and yi1 < yi2

Visualization

Tap to expand
Rectangle Area II: Union of RectanglesInput: [[0,0,2,2],[1,0,2,3],[1,0,3,1]]Rect 1Rect 2Rect 3Overlapping AreasUnion AreaTotal = 6No Double Counting• Rectangle 1: [0,0,2,2] → Area 4• Rectangle 2: [1,0,2,3] → Area 6• Rectangle 3: [1,0,3,1] → Area 2• Raw sum = 4 + 6 + 2 = 12• Union area = 6 (overlaps removed)🎯 Key: Count each unit square at most once
Understanding the Visualization
1
Input Rectangles
Multiple axis-aligned rectangles with possible overlaps
2
Find Union
Calculate total area covered by all rectangles
3
Output Area
Return total area modulo 10^9+7
Key Takeaway
🎯 Key Insight: Use coordinate compression and line sweep to efficiently calculate union area without double-counting overlaps
Asked in
Google 15 Facebook 12 Microsoft 8
23.4K Views
Medium Frequency
~35 min Avg. Time
892 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