Lesson 17 · Problem-solving methods

Sweep Line Algorithm

Picture a vertical line moving left to right across a timeline. It only needs to stop where something changes: an interval starts or ends. Keep a running count of what the line is crossing, and the busiest moment, the rooms needed and the covered length all fall out of one pass.

Sweep Line Algorithm concept diagramSix meetings on a timeline from 0 to 14: A 1 to 4, B 2 to 6, C 4 to 7, D 8 to 11, E 9 to 13, F 11 to 12. A vertical sweep line at time 9.5 crosses D and E. Below, a step graph of how many meetings are active rises and falls at every start and end, peaks at 2, and is above zero from 1 to 7 and from 8 to 13, covering 11 hours.ABCDEFpeak 2 = rooms needed12active count02468101214covered 6covered 5sweep line at 9.5crossing D, E: count 2stop only at starts (+1) and ends (−1) · peak 2 rooms · union length 6 + 5 = 11
1

Only Stop Where Something Changes

Between two consecutive start or end points nothing changes: the same intervals are active the whole way. So instead of checking every moment, the sweep line algorithm visits only those points, called events, in sorted order, and keeps a small summary of what the line is crossing right now.

For intervals that summary is often a single number, the count of active intervals. For harder problems it can be a heap or a balanced tree of active items. The pattern stays the same: sort events, walk them once, update the summary at each one.

  • Event: a position where an interval starts or ends
  • Active set: the intervals that cover the line's current position
  • Summary: a count, a heap or a tree that describes the active set
2

The Algorithm for Counting Overlaps

  1. For each interval, create a start event (start, +1) and an end event (end, −1)
  2. Sort all events by position; break ties as described in the next section
  3. Walk the events with active = 0 and peak = 0: add each event's +1 or −1 to active
  4. After each event, set peak = max(peak, active)
  5. When the walk ends, peak is the maximum overlap of intervals, here 2

Take six meetings, each a half-open range [start, end): [8, 11), [1, 4), [11, 12), [4, 7), [9, 13) and [2, 6). How many rooms are needed so that no two meetings share a room at the same time? That is the meeting rooms ii question, and the answer is the largest number of meetings running at any moment.

  • 12 events from 6 meetings
  • active never goes negative if every end follows its own start
  • Same answer as a min-heap of end times, with simpler code
3

Ties: Ends Before Starts, or the Other Way

Two events can share a position. In the meetings above, [1, 4) ends at 4 and [4, 7) starts at 4. With half-open meetings the first is over by the time the second begins, so the room is free again. Process the end first: active goes 2 → 1 → 2 and the peak stays 2. Process the start first and active briefly reads 3, which claims a third room that nobody needs.

With closed intervals the rule flips. [1, 4] and [4, 7] both contain the point 4, so they really do overlap there, and starts must come before ends to count it. The code difference is a single sort key; getting it wrong is the most common sweep-line bug.

  • Half-open [s, e): sort (position, −1) before (position, +1)
  • Closed [s, e]: starts before ends at equal positions
  • Wrong order on the example: a false peak of 3 at time 4 and again at 11
Key reference

Terms, operations, and practical uses

Key terms

  • EventA position where something starts or stops, stored with what happens there.
  • Active setEverything the sweep line is crossing at its current position.
  • Tie ruleWhich event goes first at an equal position; depends on whether end points are included.
  • Peak overlapThe largest value the active count reaches; the rooms needed.
Implementation

Code in Python, C++ and Java

def events_of(meetings):
    events = []
    for start, end in meetings:
        events.append((start, 1))
        events.append((end, -1))
    return events


def sweep(meetings, ends_first=True):
    # (time, -1) sorts before (time, +1): a room is freed before it is reused
    events = sorted(events_of(meetings), key=lambda e: (e[0], e[1] if ends_first else -e[1]))
    active = peak = covered = 0
    prev = None
    for time, delta in events:
        if active > 0:
            covered += time - prev
        active += delta
        peak = max(peak, active)
        prev = time
    return peak, covered


def rooms_two_pointers(meetings):
    starts = sorted(s for s, _ in meetings)
    ends = sorted(e for _, e in meetings)
    rooms = j = 0
    for s in starts:
        if s >= ends[j]:
            j += 1
        else:
            rooms += 1
    return rooms


meetings = [[8, 11], [1, 4], [11, 12], [4, 7], [9, 13], [2, 6]]
peak, covered = sweep(meetings)
print("rooms needed:", peak)
print("time covered by any meeting:", covered)
print("starts before ends on ties:", sweep(meetings, ends_first=False)[0])
print("two-pointer rooms:", rooms_two_pointers(meetings))
print("no meetings:", sweep([])[0])
#include <algorithm>
#include <iostream>
#include <utility>
#include <vector>
using namespace std;

pair<int, int> sweep(const vector<pair<int, int>>& meetings, bool endsFirst = true) {
    vector<pair<int, int>> events;
    for (auto [s, e] : meetings) {
        events.push_back({s, 1});
        events.push_back({e, -1});
    }
    // (time, -1) sorts before (time, +1): a room is freed before it is reused
    sort(events.begin(), events.end(), [&](const pair<int, int>& a, const pair<int, int>& b) {
        if (a.first != b.first) return a.first < b.first;
        return endsFirst ? a.second < b.second : a.second > b.second;
    });
    int active = 0, peak = 0, covered = 0, prev = 0;
    for (auto [time, delta] : events) {
        if (active > 0) covered += time - prev;
        active += delta;
        peak = max(peak, active);
        prev = time;
    }
    return {peak, covered};
}

int roomsTwoPointers(const vector<pair<int, int>>& meetings) {
    vector<int> starts, ends;
    for (auto [s, e] : meetings) { starts.push_back(s); ends.push_back(e); }
    sort(starts.begin(), starts.end());
    sort(ends.begin(), ends.end());
    int rooms = 0;
    size_t j = 0;
    for (int s : starts) {
        if (s >= ends[j]) j++;
        else rooms++;
    }
    return rooms;
}

int main() {
    vector<pair<int, int>> meetings = {{8, 11}, {1, 4}, {11, 12}, {4, 7}, {9, 13}, {2, 6}};
    auto [peak, covered] = sweep(meetings);
    cout << "rooms needed: " << peak << "\n";
    cout << "time covered by any meeting: " << covered << "\n";
    cout << "starts before ends on ties: " << sweep(meetings, false).first << "\n";
    cout << "two-pointer rooms: " << roomsTwoPointers(meetings) << "\n";
    cout << "no meetings: " << sweep({}).first << "\n";
}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
    static int[] sweep(int[][] meetings, boolean endsFirst) {
        List<int[]> events = new ArrayList<>();
        for (int[] m : meetings) {
            events.add(new int[] {m[0], 1});
            events.add(new int[] {m[1], -1});
        }
        // (time, -1) sorts before (time, +1): a room is freed before it is reused
        events.sort((a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0])
                : endsFirst ? Integer.compare(a[1], b[1]) : Integer.compare(b[1], a[1]));
        int active = 0, peak = 0, covered = 0, prev = 0;
        for (int[] ev : events) {
            if (active > 0) covered += ev[0] - prev;
            active += ev[1];
            peak = Math.max(peak, active);
            prev = ev[0];
        }
        return new int[] {peak, covered};
    }

    static int roomsTwoPointers(int[][] meetings) {
        int n = meetings.length;
        int[] starts = new int[n], ends = new int[n];
        for (int i = 0; i < n; i++) { starts[i] = meetings[i][0]; ends[i] = meetings[i][1]; }
        Arrays.sort(starts);
        Arrays.sort(ends);
        int rooms = 0, j = 0;
        for (int s : starts) {
            if (s >= ends[j]) j++;
            else rooms++;
        }
        return rooms;
    }

    public static void main(String[] args) {
        int[][] meetings = {{8, 11}, {1, 4}, {11, 12}, {4, 7}, {9, 13}, {2, 6}};
        int[] r = sweep(meetings, true);
        System.out.println("rooms needed: " + r[0]);
        System.out.println("time covered by any meeting: " + r[1]);
        System.out.println("starts before ends on ties: " + sweep(meetings, false)[0]);
        System.out.println("two-pointer rooms: " + roomsTwoPointers(meetings));
        System.out.println("no meetings: " + sweep(new int[0][], true)[0]);
    }
}
Watch it run

Step through it

Running on [8,11), [1,4), [11,12), [4,7), [9,13), [2,6)

half-open meetings · end before start at equal timesABCDEF12302468101214ACTIVE0PEAK01 +A2 +B4 −A4 +C6 −B7 −C8 +D9 +E11 −D11 +F12 −F13 −Esame six intervals as the interval lesson, now half-open: a meeting ending at 4 frees its room at 4
Step 1

Six meetings become 12 events

Each meeting [start, end) gives two events: +1 when it starts and −1 when it ends. The events are sorted by time along the bottom. Between two events nothing changes, so these 12 points are the only places the sweep needs to stop.

Output
1 / 12
4

Length of Union of Intervals

The same walk measures how much of the line is covered by at least one interval. Between two consecutive events, if active is above zero, the whole gap is covered, so add its width. Gaps where active is zero add nothing.

For the six meetings the covered stretches are 1, 7) and [8, 13), so the length of union of intervals is 6 + 5 = 11. Merging the intervals first and adding their lengths gives the same 11, which is how the [interval algorithms lesson computes it; the sweep gets it without building the merged list.

  • covered += position − previous position, whenever active > 0
  • Busiest stretches: wherever active equals the peak, here [2, 4), [4, 6), [9, 11) and [11, 12)
5

Two Sorted Arrays Instead of Events

For room counting there is a shorter form of the same line sweep. Sort the start times and the end times separately: starts 1, 2, 4, 8, 9, 11 and ends 4, 6, 7, 11, 12, 13. Walk the starts. If a start is at or after the earliest unused end, that meeting can take the freed room, so move the end pointer on. Otherwise open a new room. This also gives 2, and the ≥ in the comparison is the half-open tie rule.

  • Rooms grow only when no earlier meeting has ended
  • Use > instead of ≥ for closed intervals
6

Cost and Edge Cases

Building 2n events is O(n), sorting them O(n log n) and the walk O(n), with O(n) space for the events. When positions are small integers, a difference array does the same counting without a sort: add 1 at each start, subtract 1 at each end, and take running sums.

  • No intervals: 0 rooms, length 0
  • One interval: 1 room, its own length
  • n identical intervals: peak n
  • Zero-length interval [t, t): with ends first it never counts as active
7

Beyond Counting

The count is the simplest summary. Swap it for something richer and the same sweep solves harder problems. The skyline problem keeps a max-heap of the heights of active buildings and records a point whenever the top height changes. Finding where line segments cross keeps the active segments in a balanced tree ordered by height at the sweep line, and only checks neighbours in that order (the Bentley–Ottmann algorithm). The closest pair of points can also be found by sweeping with a strip of nearby points.

In two dimensions, sweeping a vertical line across rectangles and keeping the covered height of the active ones in a segment tree gives the area of their union in O(n log n).

  • Count: rooms, peak overlap, covered length
  • Max-heap: skyline
  • Balanced tree: segment intersections
  • Segment tree: area of a union of rectangles
8

Related Problems

These all sort events or end points and walk them once.