← Lessons

quiz vs the machine

Platinum1860

Algorithms

Line Sweep for Rectangles

Sweep across x, maintaining covered y height to compute union area.

6 min read · advanced · beat Platinum to climb

The classic problem

Given many axis aligned rectangles, compute the area of their union without double counting overlaps. A line sweep extends the one dimensional idea into two dimensions elegantly.

Vertical events

Treat each rectangle as two vertical edges. A left edge opens a vertical interval on the y axis, and a right edge closes it. Sort these edges by their x coordinate. As an imaginary vertical line sweeps left to right, the set of currently open y intervals changes only at edges.

Area between events

Between two consecutive x events the covered shape is constant: it is a set of y intervals repeated across a horizontal width. So the area contributed by a strip is the covered y length at that moment times the gap in x to the next event. Sum these strips and you have the union area.

Maintaining covered y length

The hard part is the covered y length as intervals open and close. A common solution stores the y intervals in a segment tree keyed by y coordinates, where each node tracks how many active rectangles cover it and how much of its range is covered. Adding or removing an edge updates a few nodes, and the root reports total covered length instantly.

Why it scales

Each edge causes one logarithmic update, and there are two edges per rectangle, so the whole sweep stays efficient even for many rectangles.

Key idea

Sweep a vertical line across sorted rectangle edges, maintaining the covered y length, and accumulate that length times each horizontal gap to get union area.

Check yourself

Answer to earn rating on the learn ladder.

1. What does a left rectangle edge do during the sweep?

2. How is the area of a strip between two x events computed?

3. What structure efficiently tracks the covered y length?