Skip to content

Lesson 12 of 14 · 16m

Intervals, Sweep Lines, and Prefix Sums

Sort-by-start merging, +1/−1 sweep counting, and `itertools.accumulate` turn scheduling and range queries into linear passes.

"Merge overlapping meetings." "How many rooms does this booking set need?" "Peak concurrent users from these session logs." Three different wordings, one shape: intervals. The overlap test everyone fumbles is a.start < b.end and b.start < a.end — two comparisons, not containment checks. Get that formula wrong and edge-touching intervals (a meeting ending at 10:00 versus one starting at 10:00) merge or collide depending on a bug, not a rule. Decide whether touching counts, then encode it — <= vs < is a product decision.

Merge by sorting the starts

def merge(intervals):
    intervals.sort(key=lambda x: x[0])
    out = [intervals[0][:]]
    for s, e in intervals[1:]:
        if s <= out[-1][1]:
            out[-1][1] = max(out[-1][1], e)
        else:
            out.append([s, e])
    return out

Sort by start — O(n log n) — then sweep once: extend the open interval while the next one overlaps, close it when a gap appears. The nested-loop "check every pair" version is O(n²) and still mishandles transitive overlaps: [(1,5),(3,4),(5,9)] must chain-merge into [(1,9)], and pairwise comparison misses that. The sibling variant — insert one new interval into a merged list — is the same sweep with a third phase for the tail.

Counting in-flight: the sweep line

"Minimum rooms needed" is "maximum intervals overlapping at any instant." Explode each interval into (start, +1) and (end, -1) events, sort them, accumulate:

events = [(s, 1) for s, _ in meetings] + [(e, -1) for _, e in meetings]
events.sort()
peak = cur = 0
for _, delta in events:
    cur += delta
    peak = max(peak, cur)

The max of the running total is the answer — also how you compute peak concurrency from login/logout logs, how schedulers audit capacity, and how "busiest hour" gets answered. Room-count, thread-pool sizing, license-peak audits: same sweep, same O(n log n).

Prefix sums: pay once, query forever

from itertools import accumulate
pre = [0] + list(accumulate(views))      # pre[i] = sum(views[:i])
range_sum = pre[r] - pre[l]              # O(1) per query

A dashboard that answers "pageviews between any two dates" against 5M daily rows has no business running SUM(...) per request. Build pre once in O(n); every range query becomes a subtraction. (accumulate takes a func= — max, min, operator.mul — same trick on other reducers; numpy.cumsum is the vectorized version.)

The reverse direction is the difference array: applying +v to every element of [l, r) is diff[l] += v; diff[r] -= v, and one accumulate pass materializes the final array — batch range updates in O(updates + n).

The 2D version is the integral image: S[y][x] = sum of the rectangle from the origin to (x,y), and any rectangle sums in four lookups and three subtractions. Viola and Jones shipped real-time face detection in 2001 because that trick made every feature their classifier needed nearly free — the summed-area table is what made 2001 hardware fast enough.

What to actually do

Intervals → sort by start, sweep once; counts over time → +1/−1 events, accumulate. Range-sum queries that repeat → prefix array; range updates that repeat → difference array. And when updates interleave with queries, that's where prefix sums hand off to a Fenwick tree or segment tree — O(log n) both ways.

Field notes

  • The touching-endpoint case (s <= out[-1][1] vs s < out[-1][1]) is a spec question — hotel checkout day vs booked night — decide it before coding.
  • Event ties order matters: sort (time, delta) so ends (−1) precede starts (+1) at the same timestamp, or adjacent events inflate the count.
  • accumulate(x, func=max) yields running maxima; same pass, different reducer.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.