Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Geometry

Sliding the Line.

Many interval and geometry problems look two-dimensional and messy — until you sweep. The line sweep technique slides an imaginary vertical line across the input from left to right and only stops at events: the sorted x-coordinates where something changes. Turn every interval into two events — +1 where it starts, −1 where it ends — sort them, and walk through with a running counter. The counter’s peak is the maximum overlap: the fewest meeting rooms you need. Step the line and watch the count rise and fall.

O(n log n) — the sort dominates · one linear pass over sorted events · +1 start, −1 end
event

A sorted x-coordinate where the state changes — here, an interval start or end.

+1 / −1

A start adds one to the active count; an end removes one.

active count

How many intervals overlap the sweep line right now.

peak

The maximum active count over the whole sweep — the maximum overlap.

sweep.js — sort events, walk the line
Ready
Six intervals (think meetings). Each becomes two events: +1 at its start, −1 at its end. We sort all events by position and sweep left to right, tracking how many overlap. Step to the next event.
–
sweep at
0
active now
0
max overlap

How it works

The whole trick is trading a hard continuous question — “over the entire timeline, what is the most that ever overlap?” — for a finite, discrete one. The overlap count only ever changes at an interval’s endpoints, so those endpoints are the only places worth looking. Sort them, and a single pass with a +1/−1 counter answers the question exactly. Handling ties correctly matters: process an end before a start at the same coordinate, so an interval ending exactly where another begins isn’t counted as overlapping.

1

Make events from endpoints

Turn each interval [s, e] into two events: a +1 at s and a −1 at e. The interior of the interval never needs to be examined — only where it changes.

2

Sort the events

Sort all events by x-coordinate. At ties, put −1 (end) before +1 (start) so touching intervals don’t falsely count as overlapping. This O(n log n) sort is the dominant cost.

3

Sweep with a running counter

Walk the sorted events left to right, adding each delta to a counter. The counter is the number of intervals overlapping the line at that moment.

✓

Track the peak

Keep the maximum value the counter ever reaches. That peak is the maximum overlap — for meetings, the minimum number of rooms you need. One linear pass after sorting.

Time
O(n log n)
Sweep pass
O(n)
Answers
max overlap
Generalizes
geometry

The code

# maximum overlap (min meeting rooms) via a line sweep def max_overlap(intervals): events = [] for s, e in intervals: events.append((s, +1)) # interval starts events.append((e, -1)) # interval ends events.sort(key=lambda ev: (ev[0], ev[1])) # end (-1) before start (+1) at ties active = best = 0 for x, delta in events: active += delta best = max(best, active) # the peak is the answer return best

Quick check

1. Why does the line sweep only stop at interval endpoints?

2. At a tie (an interval ends exactly where another starts), which event goes first?

3. What dominates the running time of a line sweep?

FAQ

What is a line sweep algorithm?

A technique that solves geometric and interval problems by moving an imaginary line across the input and processing a sorted sequence of events where the state changes. For interval overlap, each interval adds a +1 at its start and −1 at its end; sweeping the sorted events with a counter gives the max overlap in O(n log n).

What problems does the line sweep solve?

Maximum interval overlap and meeting rooms, merging intervals, segment-intersection detection (Bentley–Ottmann), union area of rectangles, closest pair of points, and many map-overlay and range problems. The common thread: the answer only changes at a finite set of sortable events.

How does line sweep relate to interval scheduling?

Both process sorted interval endpoints but answer different questions. Interval scheduling greedily picks the most non-overlapping intervals (sorting on end times); a line sweep counts overlaps or detects interactions as the line passes. Both sort endpoints and make one pass.

Can a line sweep run in more than one dimension?

Yes. In 2D the sweep line moves along one axis while a secondary balanced-BST "status structure" tracks what it currently intersects, ordered along the other axis — as in Bentley–Ottmann segment intersection and rectangle-union area, achieving O((n + k) log n).

The picture: intervals become a count

12233221051015202530
Six meetings: [0,30], [5,10], [15,20], [10,15], [20,25] and [12,18]. The row of numbers is the sweep counter between consecutive events, and the highlighted stretches are where it sits at its peak of 3. The count never changes inside a stretch, which is why only endpoints need visiting.

Worked example, step by step

Take the six meetings [(0,30), (5,10), (15,20), (10,15), (20,25), (12,18)]. They become 12 events, sorted by position with ends before starts at a tie. Walk them in order, adding each delta to active and keeping the largest value as best.

#PositionEventactivebest
10start +111
25start +122
310end −112
410start +122
512start +133
615end −123
715start +133
818end −123
920end −113
1020start +123
1125end −113
1230end −103

Three things show up in the trace. The position-10 pair (rows 3 and 4) is the tie rule at work: the meeting [5,10] ends and [10,15] starts at the same instant, so the counter goes 2, 1, 2 and never touches 3. The same thing happens at 15 and at 20. The peak of 3 is first reached at position 12 and held until 18, with one dip to 2 at position 15 and straight back to 3 when the next meeting starts. Finally, active returns to 0 on the last event, so the answer has to be the tracked best, not the final counter. The answer is 3: you need three rooms.

Complexity and trade-offs

CaseTimeSpaceWhy
Line sweepO(n log n)O(n)2n events, sorted once; the pass after the sort is linear.
Check every endpoint against every intervalO(n²)O(1)For each of the n starts, scan all n intervals and count the ones that contain it.
Sort by start, min-heap of end timesO(n log n)O(n)Heap size is the active count; the largest heap size is the answer.
Difference array over coordinatesO(n + R)O(R)R is the coordinate range. Excellent for small integer ranges, wasteful or impossible for large or real-valued ones.

On 1,000 random intervals (starts in 0..10,000, lengths up to 500) the sweep sorted its 2,000 events with 19,231 comparisons, and the quadratic check made 1,000,000 containment tests; both reported a peak of 45. The coordinate range of that input was 10,321, so a difference array would be comparable here, but it stops being an option when coordinates are timestamps in milliseconds or floating-point values. The sweep and the heap approach are equivalent in cost; the sweep generalises to more than counting, because each event is a hook where you can update any state.

Common mistakes

  • Starts before ends at the same coordinate

    Sorting the pairs with the larger delta first puts +1 ahead of −1. For back-to-back meetings [(0,5), (5,10)] that gives a peak of 2, when one room is enough. Sort by (position, delta) so the −1 comes first.

  • Not sorting the events

    Building the events and sweeping them in insertion order (start, end, start, end, ...) measures nothing useful. On this page's six meetings it reports a peak of 1 instead of 3.

  • Using the wrong tie rule for closed intervals

    Ends-first is right when an interval is half-open, as in meeting rooms. If the problem says the endpoints are included, [1,5] and [5,8] do overlap, and the rule must flip: starts first returns 2, ends first returns 1. Read what the endpoints mean before choosing.

  • Storing events in a map keyed by position

    A dictionary like d[s] = +1; d[e] = −1 overwrites when two intervals share an endpoint. For [(1,3), (1,4)] the two starts at 1 collapse into one and the peak comes out as 1 instead of 2. Keep a list of events, or add to the map entry instead of assigning.

  • Returning the final counter

    The counter is back at zero after the last event (it is 0 in the trace above). The answer is the maximum seen during the pass, so keep a separate best.

Where this shows up

  • Meeting rooms and capacity planning

    The minimum number of rooms, servers, or workers needed so that no job waits is the maximum overlap of the busy intervals. The same pass answers "how many concurrent users at peak" from a log of connect and disconnect times.

  • Merging and covering intervals

    Merging overlapping ranges, finding the total length covered by a set of ranges, and finding gaps between bookings are all single passes over sorted endpoints with a running count or a running end.

  • Computational geometry

    Counting or reporting intersections among line segments (the Bentley-Ottmann algorithm), computing the union area of rectangles, and several closest-pair and skyline problems sweep a line across the plane while a balanced tree holds what the line currently crosses.

  • Skyline and calendar problems

    The skyline of a city, calendar "busy" aggregations and free-slot search all convert objects into start and end events and maintain a structure over the active set, which is the same technique with a richer state than a counter.

SOLVE IT YOURSELF

Solve it: how many meetings overlap at once

Stop thinking about intervals and start thinking about events. Sort the moments something starts or ends, walk the timeline, and the answer falls out of a single counter. Python or TypeScript.

YOUR TASK

Implement max_overlap(intervals): given [start, end] pairs, return the largest number of intervals active at any one moment. An interval ending exactly when another starts does not overlap it.

HINTS — 6 IDEAS
  1. Turn each interval into two events: (start, +1) and (end, −1). The intervals themselves stop mattering.
  2. Sort the events by time, then sweep, keeping a running counter and its maximum.
  3. The subtle part is ties. At the same timestamp, ends must be processed before starts, or back-to-back meetings look like an overlap.
  4. Sorting (t, −1) before (t, +1) happens for free if you sort the pairs directly, since −1 < +1 — a small trick worth recognising rather than special-casing.
  5. This is O(n log n) from the sort alone; the sweep itself is a single linear pass with one integer of state.
  6. The same sweep shape solves merging intervals, skyline problems and rectangle unions — only the event payload changes.
CPython · WebAssembly

Keep going

Finished this one? 0 / 99 Algorithms done
NextSimulated Annealing: Cool to Improve Next on the “Points, lines and giving up” ladder · rung 3 of 3

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms