Search lands in PR-5.1 (Pagefind).

How-to Intermediate

Chapter 1 Updated

Sweep Line Template

Decompose to events, sort, sweep a running counter.

  • Full 5m
  • Revision
  • Flow

Problem Statement

Given an array of intervals, return the maximum number of intervals that overlap at any single point — the canonical application of the sweep-line technique, and the template that generalises to Meeting Rooms II, Calendar III, Car Pooling, and the Skyline Problem.

Input

An array of intervals [[start, end], …] on the number line.

Example input
intervals = [[1,4],[2,5],[7,9]]

Output

A single integer — the maximum overlap count reached at any point along the timeline.

Expected output
2

Constraints

  • 1 ≤ intervals.length ≤ 10⁵
  • intervals[i].length == 2
  • -10⁹ ≤ startᵢ ≤ endᵢ ≤ 10⁹

Intuition

Instead of processing intervals as whole units, decompose each into two events: a +1 at its start and a -1 at its end. Sort all events by time (ties broken by delta — ends before starts for closed semantics). Sweep left-to-right maintaining a running counter; the peak value is the answer.

Walkthrough — [[1,4], [2,5], [7,9]]
Events:   (1,+1)  (2,+1)  (4,-1)  (5,-1)  (7,+1)  (9,-1)
 
Sweep timeline:
Time:      1    2    3    4    5    6    7    8    9
Delta:    +1   +1         -1   -1        +1        -1
Active:    1    2    2    1    0    0    1    1    0
                ↑ peak = 2  ← answer

Solution

sweep_line.py
def sweepLine(intervals: list[list[int]]) -> int:
    events = []
    for start, end in intervals:
        events.append((start, 1))
        events.append((end, -1))
 
    # Sort: by time; on ties, ends (-1) before starts (+1)
    events.sort(key=lambda x: (x[0], x[1]))
 
    active = max_active = 0
    for _, delta in events:
        active += delta
        max_active = max(max_active, active)
 
    return max_active

Complexity

MetricValueReason
TimeO(n log n)Sorting the 2n events dominates
SpaceO(n)Events array holds two entries per interval

Edge Case Thinking

ScenarioHandling
Empty inputReturn 0 — no events to process.
Touching intervals [1,2] & [2,3]Correct sort key (end before start at same time) yields peak 1, not 2.
All intervals identicaln start events at the same time → peak = n.
Very large coordinatesEvents approach scales; a difference array is faster only when coords are small integers.
Negative coordinatesWorks unchanged — timeline orientation doesn’t matter.

Comments

Comments are disabled in this environment. Set PUBLIC_GISCUS_REPO, PUBLIC_GISCUS_REPO_ID, and PUBLIC_GISCUS_CATEGORY_ID to enable.