Algorithmic patterns · 5 / 15 Theory

Intervals and sweep line

Interval problems (meetings, bookings, time ranges) are almost always solved with two ideas: sort by start and walk once, or turn each interval into two events (starts, ends) and sweep the events in order (*sweep line*).

def merge(intervals):
    result = []
    for start, end in sorted(intervals):          # sort by start
        if result and start <= result[-1][1]:
            result[-1][1] = max(result[-1][1], end)   # overlaps: extend the last one
        else:
            result.append([start, end])
    return result

print(merge([(1, 3), (2, 6), (8, 10), (15, 18)]))   # [[1, 6], [8, 10], [15, 18]]

def max_overlap(intervals):
    events = []
    for start, end in intervals:
        events.append((start, 1))
        events.append((end, -1))
    active = maximum = 0
    for _, change in sorted(events):             # at the same time, -1 comes before +1
        active += change
        maximum = max(maximum, active)
    return maximum

print(max_overlap([(0, 30), (5, 10), (15, 20)]))   # 2
  • Two intervals [a, b] and [c, d] overlap if a <= d and c <= b (if they touch at an end, decide whether that counts as an overlap).
  • With events, the tie-break matters: if one meeting ends at the same time another starts, process the end first (-1 sorts before +1).
  • Sorting dominates the cost: O(n log n).

You practice it in Merge intervals and Meeting rooms needed.