AlgoInsight

DSA problem

Rectangle Area II

HardLine SweepPattern: Line Sweeptop600GoogleAmazonMicrosoftAirbnb

You are given a 2D array rectangles where rectangles[i] = [x1_i, y1_i, x2_i, y2_i] denotes an axis-aligned rectangle with bottom-left corner (x1, y1) and top-right corner (x2, y2). Return the total area covered by all rectangles in the plane, where any overlapping area is counted exactly once. The answer may be very large, so return it modulo 10^9 + 7.

A naive approach of "union of rectangles" by drawing on a bitmap is hopeless because coordinates can be as large as 10^9. The classical trick is to sweep a vertical line from left to right while maintaining, in a separate data structure, the set of y-intervals currently active. When the sweep advances from x_curr to x_next the contribution to the total area is (x_next - x_curr) * unionLength(active y-intervals), evaluated before any events at x_next are processed.

To make the inner step fast, coordinate-compress the y-values: the union of all rectangles' y-coordinates partitions the y-axis into O(n) atomic intervals. A segment tree built over these atomic intervals stores, per node, a count of currently-active rectangles fully covering that node's range plus the length of "actively covered y" within its range. When a node's count is positive the entire node range is covered; otherwise its covered-length is the sum of its children's covered-lengths.

Events are generated per rectangle: an OPEN event (x1, +1, y1, y2) and a CLOSE event (x2, -1, y1, y2). Sort events by x. Sweep: for each distinct x, accumulate area using the current root covered-length, then apply all events at x to the segment tree (update each node's count by +/-1 along its update path). The total runtime is O(n log n) and the answer is taken modulo 10^9 + 7.

Examples

Example 1
Input: rectangles = [[0,0,2,2],[1,0,2,3],[1,0,3,1]]
Output: 6
Explanation: Drawn out, the three rectangles cover a region of total area 6 once overlaps are de-duplicated. The bottom-left rectangle has area 4, the right-most rectangle contributes a 1x2 strip and a 1x1 strip not previously covered.
Example 2
Input: rectangles = [[0,0,1000000000,1000000000]]
Output: 49
Explanation: A single 10^9 x 10^9 rectangle has area 10^18; (10^18) mod (10^9 + 7) = 49.
Example 3
Input: rectangles = [[0,0,2,2],[2,0,4,2]]
Output: 8
Explanation: Two rectangles sharing only the vertical edge x=2 do not overlap by area; total = 4 + 4 = 8.

Constraints

4 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

line-sweepsegment-treecoordinate-compressiongeometryordered-set

Browse all DSA problems