Sweep line: process boundary events
Picture
Meeting [1,4) adds one active room at 1 and removes one at 4.
Predict
Why must equal-position events have a defined order?
Walk through the small example
It decides whether boundaries overlap. The answer changes only at boundaries, so process events rather than every coordinate.
Mental model and complete Python solution
A sweep line is a timeline cursor. Each boundary says how the active world changes. Between boundaries, nothing relevant changes, so no work is needed there.
What the function promises: Return the maximum number of simultaneous half-open intervals [start,end). Zero-length intervals contribute nothing.
def max_overlap(intervals):
events = []
for start, end in intervals:
if start < end:
events += [(start, 1), (end, -1)]
active = best = 0
for _, change in sorted(events, key=lambda event: (event[0], event[1])):
active += change
best = max(best, active)
return best
assert max_overlap([(1,4),(2,3),(3,5)]) == 2
assert max_overlap([(1,2),(2,3)]) == 1
Work and storage: O(n log n) time and O(n) event storage.
When to recognize it: The answer changes only at boundaries, so process events rather than every coordinate.
Check before applying it: Incorrect tie handling silently changes whether touching intervals overlap.
Change one rule
Coordinates are integers from 0 through 1000 with millions of intervals.
See what changes
Use a dense difference array and one prefix scan.
Connect
Merge Intervals: Both sort interval boundaries but maintain different summaries.
Difference arrays: store changes: Preaggregate changes when coordinates form a small dense range.