Skip to contentKEEP THE CRAFTTHE SANCTUARY

Sweep Line

Represent nonempty half-open intervals as ordered +1 and -1 events to track active counts. End-before-start ties encode touching semantics, and cumulative activity answers a different question from an interval union.

1 practice exercise2 interview problems

Recognize it when The answer depends on how many intervals are active at a coordinate, rather than only which coordinates are covered.

Checking your account…

Sweep Line Code Labs

Count Changes Instead of Every Time Point

After understanding interval boundaries, observe that an active count changes only when an interval begins or ends. A sweep collects those events and visits them in coordinate order. Between distinct coordinates the active state is constant, so no scan of every time unit is needed.

Encode Half-Open Ties with Event Order

These Labs accept nonempty [start,end) intervals. An end at time t is no longer active at t; a start at t is active immediately after that boundary. Sorting tuple events places (t,-1) before (t,+1), so touching intervals never produce a temporary extra overlap. Empty intervals would need separate handling: this reference loop assumes start < end rather than accepting an end before its own start.

Trace Sweep Events

Reference
def active_trace(intervals):
    events=[]
    for start,end in intervals:events.append((start,1));events.append((end,-1))
    active=0;trace=[]
    for coordinate,delta in sorted(events):active+=delta;trace.append([coordinate,delta,active])
    return trace
Practice

Implement active_trace(intervals). Intervals are half-open; process end before start at equal coordinates and return [coordinate,delta,active]. Each interval is nonempty with start < end.

Public tests

  • Apply half-open tie order

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Sweep Events

def active_trace(intervals):
    events=[]
    for start,end in intervals:events.append((start,1));events.append((end,-1))
    active=0;trace=[]
    for coordinate,delta in sorted(events):active+=delta;trace.append([coordinate,delta,active])
    return trace

Process an End and a Start at the Same Coordinate

The existing trace on [[0, 3], [2, 5], [3, 4]] contains a tie at 3. Its ordered event states never count the ended first interval with the new third interval.

Step Executed statement State Why
Create events for start,end in intervals:events.append((start,1));events.append((end,-1)) events=[(0,1),(3,-1),(2,1),(5,-1),(3,1),(4,-1)] Every interval contributes its start and end separately.
First starts for coordinate,delta in sorted(events):active+=delta;trace.append([coordinate,delta,active]) at 0 active=1; at 2 active=2 The two nonempty intervals overlap between 2 and 3.
End at 3 for coordinate,delta in sorted(events):active+=delta;trace.append([coordinate,delta,active]) coordinate=3, delta=-1, active=1 The end event sorts before the same-coordinate start.
Start at 3 for coordinate,delta in sorted(events):active+=delta;trace.append([coordinate,delta,active]) coordinate=3, delta=1, active=2 The new interval replaces an ended one without creating count 3.
Final ends for coordinate,delta in sorted(events):active+=delta;trace.append([coordinate,delta,active]) at 4 active=1; at 5 active=0 Each remaining end removes exactly one live contribution.
Return return trace six ordered event states The trace reports transitions; the peak Lab separately takes their maximum.
Print Output
print(active_trace([[0, 3], [2, 5], [3, 4]])) [[0, 1, 1], [2, 1, 2], [3, -1, 1], [3, 1, 2], [4, -1, 1], [5, -1, 0]]

Measure the Count after Applying Each Change

The peak Lab increments active by the current delta before comparing it to best. Reading only the final active total loses the entire history, because all properly paired starts and ends eventually cancel. The trace may show several event states at one coordinate; to describe a positive-length span, use the state after all events at that coordinate are complete.

Find Maximum Overlap

Reference
def maximum_overlap(intervals):
    events=[]
    for start,end in intervals:events.append((start,1));events.append((end,-1))
    active=best=0
    for _,delta in sorted(events):active+=delta;best=max(best,active)
    return best
Practice

Implement maximum_overlap(intervals). Return the maximum number of active half-open intervals. Each interval is nonempty with start < end.

Public tests

  • Measure active state after each event

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Find Maximum Overlap

def maximum_overlap(intervals):
    events=[]
    for start,end in intervals:events.append((start,1));events.append((end,-1))
    active=best=0
    for _,delta in sorted(events):active+=delta;best=max(best,active)
    return best

Preserve Multiplicity or Combine Deltas Deliberately

Two starts at the same coordinate are two additions. A dictionary assignment keyed by coordinate would overwrite one; either keep the separate events used by the Lab or accumulate deltas. For the half-open peak-count contract, grouping tied deltas and measuring after the group is another valid formulation. Do not mix grouped semantics with promises to expose each individual event.

Choose the Event Question in an Interview

Merging intervals gives a union but loses overlap counts. A sweep answers how active state changes; weighted counts or geometric sweeps may need richer state and different costs. For these unweighted Labs, O(n) event storage plus O(n log n) sorting dominates. Explain the endpoint convention and one tied end/start before reporting concurrency.

Python Version Note

Python 3.11+

Python sorts tuples lexicographically, so (coordinate,-1) precedes (coordinate,+1); preserving separate events also preserves simultaneous multiplicity.

Verify in Python docs(opens in a new tab)

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Sort and sweep two events per intervalO(n log n)O(n log n)There are exactly 2n count events; sorting dominates the linear event scan.

Space

O(n) events and trace output; the peak Lab uses constant additional sweep state.

Assumptions

  • Intervals are nonempty half-open ranges with start < end; tied ends run before starts, and intermediate same-coordinate trace counts are event states rather than new spans.
  • Python sorts tuples lexicographically, so (coordinate,-1) precedes (coordinate,+1); preserving separate events also preserves simultaneous multiplicity.

Invariants Worth Saying Aloud

  1. active is the sum of all processed start/end deltas; nonempty intervals start before they end.
  2. At equal coordinates, -1 events precede +1 events so a half-open end does not overlap a new start.

When To Use Or Avoid Sweep Line

Use It When

  • Find peak concurrency or trace active counts for nonempty half-open intervals.
  • Generalize to additive weighted activity only after defining each event delta and tie semantics.

Choose Another Tool When

  • Use interval merging when only the union is required and multiplicity can be discarded.
  • Do not apply these unweighted count Labs directly to geometric intersections requiring an ordered active structure.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Starting before ending at a touching boundary

For [0,2) and [2,4), processing +1 first at 2 momentarily reports two active intervals even though they never overlap.

Prevent it: For nonempty half-open ranges, sort -1 before +1 at equal coordinates.

Avoid

ordered = sorted(events,key=lambda event:(event[0],-event[1]))

Use instead

ordered = sorted(events)

Returning the final active count as the peak

Properly paired start/end events finish at zero, even when the middle of the sweep had overlap.

Prevent it: Track best after each delta instead of returning only the final active balance.

Avoid

answer = active

Use instead

answer = best

Overwriting simultaneous starts in a dictionary

Assigning one delta per coordinate collapses two starts at time 2 into a single +1 and undercounts activity.

Prevent it: Keep events separate or add their deltas into a coordinate total.

Avoid

deltas = dict(events)

Use instead

deltas={}
for coordinate,delta in events:
    deltas[coordinate]=deltas.get(coordinate,0)+delta

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.