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 - Line Sweep Algorithm INPUT R1 R2 R3 0 1 2 3 rectangles = [ [0,0,2,2], [1,0,2,3], [1,0,3,1] ] (x1,y1,x2,y2) format ALGORITHM STEPS 1 Extract X coords Sort unique: [0,1,2,3] 2 Create Events Open/Close at each x 3 Sweep Left to Right Track active intervals 4 Calculate Area width x merged height Sweep Line Process sweep x=0 x=1 x=2 x=3 FINAL RESULT 2 3 1 0 1 2 3 Area Calculation [0,1]: 1 x 2 = 2 [1,2]: 1 x 3 = 3 [2,3]: 1 x 1 = 1 Total = 2+3+1 OUTPUT 6 Key Insight: Line Sweep processes rectangles by sweeping a vertical line across all x-coordinates. At each x position, we track active y-intervals and merge overlapping ones to avoid double counting. Area between consecutive x-coords = (x2-x1) * (total merged y-interval length). Time: O(N^2 log N) TutorialsPoint - Rectangle Area II | Line Sweep Algorithm
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