Technique
Sweep Line (events + active set)
Sort start/end events by coordinate and process them in order while an active-set structure (counter, heap, ordered set, segment tree) tracks what is open.
0/12 solved
Recognise it
The signal
max overlap with identity of intervals
1Brute force
Check every pair or every coordinate.
2The observation
Pairwise or per-coordinate checks: only event points change the active set.
3Why it works
When the sweep is at x, the active structure contains exactly the objects intersecting the line at x.
Reach for it when
- +skyline / union area of rectangles
- +closest pair, segment intersections
- +rooms allocation
Not when
- ×no ordering dimension
- ×events cannot be sorted offline (online problem)
Practice
- Meeting Rooms IIPremiumMedium
- Restaurant CustomersCSESMedium
- Car PoolingUber, LyftMedium
- Room AllocationCSESMedium
- The Skyline ProblemGoogle, AmazonHard
- Area of RectanglesCSESHard
- Rectangle Area IIHard
- Intersection PointsCSESHard
- Maximum Sum QueriesHard
- Number of Flowers in Full BloomHard
- Minimum Euclidean DistanceCSESHard
- Minimum Interval to Include Each QueryHard
Pitfalls
Misconceptions
- !tie-breaking start vs end at the same coordinate changes the answer
Go deeper3 combinations · resources
Combinations
Sweep Line (events + active set)+Top-K Elements
skyline / max active value over time
- Sweep Line (events + active set):
- processes building edges in x order
- Top-K Elements:
- max-heap (with lazy deletion) of active heights
Sweep Line (events + active set)+Segment Tree / Fenwick (BIT)+Coordinate Compression
area/perimeter of union of rectangles
- Sweep Line (events + active set):
- moves over x events
- Segment Tree / Fenwick (BIT):
- maintains covered length on y with range add
- Coordinate Compression:
- maps y endpoints to segment tree leaves
Sweep Line (events + active set)+Segment Tree / Fenwick (BIT)
count intersections of axis-parallel segments, or points dominated by a query in 2D, offline
- Sweep Line (events + active set):
- process vertical segments and horizontal endpoints in x order
- Segment Tree / Fenwick (BIT):
- a BIT over y counts the active horizontals in [y1, y2]