Courses / DSA Patterns for Working Engineers / Chapter 5
Module 2 · Pointers, windows, intervals and linked lists · Chapter 5 of 39
Intervals: Merging, Inserting and Counting Overlaps
Builds on Two Pointers: Pairs, Partitions and In-Place Scans. Next up: In-Place Linked List Changes: Reversal, Reordering and Rotation.
Part 1 · Introduction to intervals
What an interval is
Calendars, room bookings, maintenance windows and sensor readings all describe a stretch of time as a start and an end. Questions about many stretches at once, such as which ones clash or how many run together, are solved with a small set of techniques that this chapter teaches.
An interval is a pair of numbers, [start, end], with start before end. The numbers can be minutes since midnight, seconds, days or array positions. Before writing any code you must decide what the two ends mean, because the answer changes every comparison. There are two common conventions.
| Convention | Written | Contains | Length | Do [9, 10] and [10, 11] overlap |
|---|---|---|---|---|
| Closed | [start, end] | start, end and all between | end - start + 1 for whole numbers | Yes, both contain 10 |
| Half-open | [start, end) | start and all between, but not end | end - start | No, 10 belongs only to the second |
Written[start, end]
Containsstart, end and all between
Lengthend - start + 1 for whole numbers
Do [9, 10] and [10, 11] overlapYes, both contain 10
Sorting and sweeping
Almost every interval problem begins with the same move: sort by start time. After sorting, every interval before the current one starts no later, so the current one overlaps one of them exactly when it starts before the latest end seen so far. That is why a single left-to-right pass can merge, insert or check a whole schedule.
Sorting needs a comparator that returns a number, here a[0] - b[0]. JavaScript's sort has been stable since ES2019, so intervals with equal starts keep their input order, which makes results repeatable. The run below sorts five bookings and shows ties staying in their original order.
// Equal starts keep their input order, because Array.prototype.sort is // stable (guaranteed since ES2019). const bookings: [number, string][] = [ [9, 'yoga'], [8, 'viva'], [9, 'quiz'], [8, 'lab'], [9, 'talk'], ] const sorted = bookings.toSorted((a, b) => a[0] - b[0]) console.log(sorted.map(([t, name]) => `${t} ${name}`).join(', '))
Equal start times keep their input order
8 viva, 8 lab, 9 yoga, 9 quiz, 9 talk
Output of one run
The second tool is the sweep line. Instead of comparing intervals with each other, turn each one into two events: a start event that adds one to a counter and an end event that subtracts one. Sort all events by time and walk through them. The counter is the number of intervals active at that moment, and its highest value is the most intervals that ever overlap. Sorting 2n events costs O(n log n) and the walk is O(n).
Events at the same time need a rule. With half-open ranges, an interval ending at 10:00 is already over when one starting at 10:00 begins, so you must process the end before the start. Get this wrong and back-to-back bookings look like clashes.
The tie rule in code
The first function below counts the most bookings active at one time, and takes a flag that picks the order of events at equal times. The second block runs it on three back-to-back bookings in both orders.
type Interval = [number, number] // The most bookings active at one instant, by sweeping start and end // events in time order. endsFirst picks the order at equal times. export function peakOverlap(bookings: Interval[], endsFirst: boolean) { const events: [number, number][] = [] for (const [s, e] of bookings) events.push([s, +1], [e, -1]) events.sort((a, b) => a[0] !== b[0] ? a[0] - b[0] : endsFirst ? a[1] - b[1] : b[1] - a[1], ) let active = 0 let peak = 0 for (const [, delta] of events) { active += delta peak = Math.max(peak, active) } return peak }
The sweep: ends first or starts first at equal times
import { overlaps, overlapsClosed } from './overlap.ts' import { peakOverlap } from './sweep.ts' const nine: [number, number] = [9, 10] const ten: [number, number] = [10, 11] console.log('9-10 and 10-11 as half-open:', overlaps(nine, ten)) console.log('9-10 and 10-11 as closed: ', overlapsClosed(nine, ten)) const chain: [number, number][] = [[9, 10], [10, 11], [11, 12]] console.log('ends first: peak', peakOverlap(chain, true)) console.log('starts first: peak', peakOverlap(chain, false))
The overlap tests and both tie orders on the same bookings
9-10 and 10-11 as half-open: false 9-10 and 10-11 as closed: true ends first: peak 1 starts first: peak 2
Output of one run
With ends first the three bookings share no instant, so the peak is 1. With starts first the counter reaches 2 at 10 and again at 11, which is a false clash created only by the processing order. The same mistake appears when you use <= on half-open ranges. Whenever a problem says "back to back is allowed", write the tie rule in a comment next to the sort.
Both tools run in O(n log n) time because of the sort. The sweep uses O(n) extra space for the events.
Are the ranges [9, 10] and [10, 11] overlapping?
- As half-open ranges they are not, because 10 belongs only to the second one.
- As closed ranges they are, because both contain 10. Decide from what the numbers mean.
Why does almost every interval solution start by sorting by start time?
Part 2 · Merging a clinic's appointment blocks
The problem
A clinic keeps one doctor's day as a list of blocks, each with a start and an end in minutes since midnight. Receptionists enter blocks as patients book, so the list is unsorted and some blocks overlap or sit right next to each other. The task is to turn the list into busy spans with no overlaps and no touching, and then to list the free spans left in the working day.
A first idea compares every block with every other one, merges any pair that overlaps and repeats until nothing changes. It works but is slow, because one merge can create a new overlap with a block you already passed, so you keep rescanning. Sorting removes the rescanning. Once blocks are ordered by start, a block either extends the span being built or starts a new one.
Keep the current span's end in a variable. For each next block in start order: if its start is at or before that end, the two touch or overlap, so the span's end becomes the larger of the two ends. If the start is after the end, the span is finished and a new one begins. The scene walks through seven blocks given in hours.
Watch for end growing while blocks overlap, and a gap closing a span
Read it as steps
The code
The function below does the merge, and the second function walks the busy spans to find the free ones. Both take times in minutes since midnight.
type Interval = [number, number] // Merge overlapping or touching blocks (minutes since midnight). export function mergeBlocks(blocks: Interval[]): Interval[] { const sorted = blocks.toSorted((a, b) => a[0] - b[0]) const out: Interval[] = [] for (const [start, end] of sorted) { const last = out[out.length - 1] if (last && start <= last[1]) last[1] = Math.max(last[1], end) else out.push([start, end]) } return out } // The free spans left inside the working day. export function freeSpans( busy: Interval[], dayStart: number, dayEnd: number, ): Interval[] { const free: Interval[] = [] let cursor = dayStart for (const [start, end] of busy) { if (start > cursor) free.push([cursor, start]) cursor = Math.max(cursor, end) } if (cursor < dayEnd) free.push([cursor, dayEnd]) return free }
Merge blocks, then list the free spans inside the day
The merge sorts a copy with toSorted so the caller's array is untouched. The condition start <= last[1] merges blocks that touch, such as 9:00-10:00 and 10:00-10:30. If your problem wants touching blocks kept apart, change it to <. The free-span function is a second pass over the already merged list, with a cursor that remembers where the last busy span ended.
import test from 'node:test' import assert from 'node:assert/strict' import { mergeBlocks, freeSpans } from './merge-blocks.ts' type Blocks = [number, number][] test('overlapping and touching blocks become one', () => { assert.deepEqual(mergeBlocks([[540, 600], [570, 660]]), [[540, 660]]) assert.deepEqual(mergeBlocks([[540, 600], [600, 630]]), [[540, 630]]) }) test('a block inside another disappears', () => { assert.deepEqual(mergeBlocks([[540, 720], [600, 630]]), [[540, 720]]) }) test('unsorted input is handled and not changed', () => { const input: Blocks = [[780, 840], [540, 600], [570, 650]] assert.deepEqual(mergeBlocks(input), [[540, 650], [780, 840]]) assert.deepEqual(input, [[780, 840], [540, 600], [570, 650]]) }) test('no blocks: no spans, and the whole day is free', () => { assert.deepEqual(mergeBlocks([]), []) assert.deepEqual(freeSpans([], 540, 1020), [[540, 1020]]) }) test('free spans fill the gaps of a 9:00 to 17:00 day', () => { const busy = mergeBlocks([[600, 660], [630, 700], [840, 900]]) assert.deepEqual(freeSpans(busy, 540, 1020), [ [540, 600], [700, 840], [900, 1020], ]) })
Tests for nested, touching, unsorted and empty input
✔ overlapping and touching blocks become one (1.1467ms) ✔ a block inside another disappears (0.1408ms) ✔ unsorted input is handled and not changed (0.1896ms) ✔ no blocks: no spans, and the whole day is free (0.1934ms) ✔ free spans fill the gaps of a 9:00 to 17:00 day (0.1258ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
Output of one run; the times in brackets vary
Reading the tests as a checklist
Each test guards one way the merge can go wrong, and the same list works for most interval code you will write.
- Overlapping and touching. Two blocks that share time, and two that share only an end point, both collapse to one span. The touching case is the one people forget, and the one a closed-versus-half-open decision changes.
- Nested. A short block inside a long one must not shrink the long one. This is the case that fails when the code assigns the new end instead of taking the larger.
- Unsorted input. Receptionists do not enter blocks in order, so the function must sort. The test also checks the caller's array is unchanged, since an unexpected mutation is a bug that shows up far from where it was made.
- Empty input. The loop never runs and the result is an empty list. The free-span function then returns the whole day.
Merging is also the building block for the next lessons. Inserting a window, finding common free time and counting rooms each reuse this sorted pass or the idea behind it, so it is worth getting the four cases above settled before moving on.
Related on LeetCode: Merge Intervals.
Why does the merge update the span's end with a maximum rather than just copying the new block's end?
- A block can lie entirely inside the current span, and then its end is smaller than the span's end.
- Copying it would shorten the span and lose coverage.
What changes if blocks that only touch, like 9:00-10:00 and 10:00-10:30, must stay separate?
- Use
start < last[1]instead ofstart <= last[1]. - Nothing else changes, because the sort and the pass are the same.
What is the time cost of the merge, and which step dominates?
Part 3 · Inserting a maintenance window
The problem
A server has a schedule of maintenance windows. The list is sorted by start and no two windows overlap or touch. An operator adds one more window, and the result must keep both properties. Some existing windows may now overlap the new one and must be combined with it.
You could append the new window and run the merge from the previous lesson. That is correct but spends O(n log n) re-sorting a list that is already sorted. A single pass can do it in O(n), because the sorted list falls into three groups relative to the new window.
| Group | Test | What to do |
|---|---|---|
| Before | The existing window ends before the new one starts | Copy it unchanged |
| Overlapping | It starts at or before the new window's end | Absorb it: lower the start, raise the end |
| After | Everything left | Copy it unchanged |
Each group is contiguous. The windows before the new one come first because the list is sorted, then a run of windows that touch the new one, then the rest. Three loops over one index walk the three groups with no backtracking.
Here is the idea on a small schedule with windows 60-90, 120-150 and 200-260, and a new window 80-130. The first window ends at 90, which is not below 80, so it is not in the first group. The loop that absorbs windows starts at 60-90: its start 60 is at or before the new end 130, so the new window becomes 60-130. The next window, 120-150, also starts before 130, so the new window becomes 60-150. The window 200-260 starts after 150, so the absorbing stops and the remaining window is copied. The result is 60-150 and 200-260.
The code
type Interval = [number, number] // schedule is sorted and has no overlapping or touching windows. export function insertWindow(schedule: Interval[], add: Interval) { const out: Interval[] = [] let i = 0 while (i < schedule.length && schedule[i][1] < add[0]) { out.push(schedule[i++]) // ends before the new window starts } let [start, end] = add while (i < schedule.length && schedule[i][0] <= end) { start = Math.min(start, schedule[i][0]) // overlaps or touches it end = Math.max(end, schedule[i][1]) i++ } out.push([start, end]) while (i < schedule.length) out.push(schedule[i++]) // starts after it return out }
One pass in three loops
The first loop copies windows whose end is below the new start. Strict < matters: a window ending exactly where the new one starts touches it, so it belongs to the second group and is absorbed. The second loop grows the new window while the next window starts at or before the new end. The third loop copies the rest. Every window is looked at once, so the cost is O(n) time and O(n) space for the answer.
import test from 'node:test' import assert from 'node:assert/strict' import { insertWindow } from './insert-window.ts' const base: [number, number][] = [[60, 90], [120, 150], [200, 260]] test('a window in a gap is placed in order', () => { assert.deepEqual(insertWindow(base, [160, 180]), [[60, 90], [120, 150], [160, 180], [200, 260]]) }) test('a window bridging two others swallows both', () => { assert.deepEqual(insertWindow(base, [80, 130]), [ [60, 150], [200, 260], ]) }) test('a window before everything and one after everything', () => { assert.deepEqual(insertWindow(base, [10, 20])[0], [10, 20]) assert.deepEqual(insertWindow(base, [300, 320]).at(-1), [300, 320]) }) test('an empty schedule just holds the window', () => { assert.deepEqual(insertWindow([], [5, 9]), [[5, 9]]) }) test('touching windows join', () => { assert.deepEqual(insertWindow(base, [150, 200]), [ [60, 90], [120, 260], ]) })
Gap, bridging, ends of the list, empty and touching
✔ a window in a gap is placed in order (1.4426ms) ✔ a window bridging two others swallows both (0.1726ms) ✔ a window before everything and one after everything (0.1736ms) ✔ an empty schedule just holds the window (0.1445ms) ✔ touching windows join (0.1609ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
Output of one run; the times in brackets vary
Checking against the simple version
Five tests do not prove an algorithm. The strongest check is to compare it with a version you trust on thousands of random inputs. Here the trusted version is "append and merge". The program builds random sorted schedules with a gap of at least 1 between windows, picks a random new window, and compares both results. It uses mulberry32, the small seeded generator from the first chapter of the course, so every run is the same.
import { mulberry32 } from './rng.ts' import { mergeBlocks } from './merge-blocks.ts' import { insertWindow } from './insert-window.ts' const rand = mulberry32(2026) const pick = (lo: number, hi: number) => lo + Math.floor(rand() * (hi - lo + 1)) let mismatches = 0 const cases = 5000 for (let t = 0; t < cases; t++) { const schedule: [number, number][] = [] let at = pick(0, 20) for (let k = pick(0, 8); k > 0; k--) { const start = at + pick(1, 15) // a gap of at least 1: no touching const end = start + pick(1, 15) schedule.push([start, end]) at = end } const s = pick(0, 120) const add: [number, number] = [s, s + pick(1, 40)] const want = mergeBlocks([...schedule, add]) const got = insertWindow(schedule, add) if (JSON.stringify(want) !== JSON.stringify(got)) mismatches++ } console.log(`${cases} random schedules, ${mismatches} differences`)
Random schedules: insert in one pass against append and merge
5000 random schedules, 0 differences
Output of one run
Zero differences over five thousand schedules is good evidence. The gap of at least 1 matters: the one-pass version assumes its input has no touching windows, and the generator keeps that promise.
A stress test is only as good as its generator, so it is worth asking what this one covers. Schedules have between zero and eight windows, so the empty list and short lists appear. The new window starts anywhere from 0 to 120 and lasts 1 to 40, so it lands before everything, after everything, inside a gap, inside a window and across several windows. Over five thousand cases, each of those placements has many chances to come up.
When the two versions disagree, the failing input is the most useful thing you can have. Print it, shrink it by hand to the smallest schedule that still fails, and then fix the code. A habit worth building: write the slow, obviously correct version first, then the fast one, then a loop that compares them.
Part 4 · Free slots common to two panel members
Two sorted lists, two pointers
A review panel of four members needs a one-hour slot together. Each has a sorted list of the times they are free. The shared free time is the intersection of the lists: the stretches that appear in both.
Take two sorted lists of disjoint ranges, a and b, and keep one pointer in each. At each step, the overlap of the two current ranges is from the later of the starts to the earlier of the ends. If that is a real range, because its start is before its end, record it. Then move on from whichever of the two ranges ends first: it cannot overlap anything further in the other list, since the other list's later ranges start no earlier than its current range ends, which is no earlier than this one ends. This is the idea from the two pointers chapter, applied to ranges, and it costs O(a + b).
Ranges that only touch give a zero-length overlap, so the test start < end skips them.
From one pair to a whole panel
A panel is a list of lists. There are two ways to get the free time common to everyone, and they should agree.
- Fold. Turn each member's busy blocks into free spans, using the merge and gap code from the merging lesson, then intersect the lists one after another. Intersecting two sorted lists gives a sorted list, so the fold works for any panel size.
- Pool. Put every member's busy blocks into one list, merge them, and take the gaps. A moment is free for everyone exactly when it is busy for nobody.
Pool costs O(n log n) for n total blocks. Fold costs the same sorts plus one intersection per member, which adds up on a large panel. Fold is easier to explain when each member already has availability lists. Pool is shorter when you start from busy blocks.
The code
type Interval = [number, number] // Two sorted lists of disjoint ranges: the parts they share. export function intersect(a: Interval[], b: Interval[]): Interval[] { const out: Interval[] = [] let i = 0 let j = 0 while (i < a.length && j < b.length) { const start = Math.max(a[i][0], b[j][0]) const end = Math.min(a[i][1], b[j][1]) if (start < end) out.push([start, end]) if (a[i][1] < b[j][1]) i++ // the range that ends first is finished else j++ } return out }
Intersection of two sorted lists by two pointers
import { mergeBlocks, freeSpans } from './merge-blocks.ts' // Free time common to everyone: intersect each member's free spans. export function commonFree( busy: Interval[][], dayStart: number, dayEnd: number, ) { return busy .map((b) => freeSpans(mergeBlocks(b), dayStart, dayEnd)) .reduce((acc, free) => intersect(acc, free)) } // The same answer from one pool: merge every busy block, take the gaps. export function commonFreePooled( busy: Interval[][], dayStart: number, dayEnd: number, ) { return freeSpans(mergeBlocks(busy.flat()), dayStart, dayEnd) }
The panel by fold and by pool
The intersect function advances the pointer of the range that ends first. When two ranges end at the same time, the else branch advances j, and that is safe: the range in a that ended at the same instant will fail the start < end test against the next range in b, because that range starts later, and then i moves. The functions reuse mergeBlocks and freeSpans from the merging lesson through an import.
Why must the inputs be sorted and disjoint? The pointer rule assumes that once the current range in one list is finished, nothing earlier in the other list matters. That holds when each list is in order and its ranges do not overlap. A member's busy blocks can overlap, which is why commonFree merges them and takes the free spans before it intersects. Feeding raw blocks to intersect would break the assumption and return wrong answers without any error.
The work per step is constant and each step finishes at least one range, so the loop runs at most a.length + b.length times. Folding a panel of m members costs the sum of the intermediate list sizes. The running answer is the free time common to the members so far, which has at most one range more than their busy blocks, so it holds at most n + 1 ranges, and the fold costs O(n log n + m n) at worst. The pooled method pays for one sort of all blocks and one pass, O(n log n).
A panel of three
A run on three calendars, with the day from 9:00 to 17:00, prints the common free time.
import { commonFree } from './free-slots.ts' const hm = (m: number) => `${Math.floor(m / 60)}:${String(m % 60).padStart(2, '0')}` const panel: [number, number][][] = [ [[540, 600], [660, 720], [780, 840]], // Asha [[570, 630], [700, 760], [900, 960]], // Bilal [[540, 560], [720, 780], [840, 870]], // Charu ] for (const [s, e] of commonFree(panel, 540, 1020)) { console.log(`${hm(s)} to ${hm(e)} is free for all three`) }
Three calendars: times are minutes since midnight
10:30 to 11:00 is free for all three 14:30 to 15:00 is free for all three 16:00 to 17:00 is free for all three
Output of one run
Finally, the two methods are compared on three thousand random panels of one to four members.
import { mulberry32 } from './rng.ts' import { commonFree, commonFreePooled } from './free-slots.ts' const rand = mulberry32(7) const pick = (lo: number, hi: number) => lo + Math.floor(rand() * (hi - lo + 1)) let differ = 0 for (let t = 0; t < 3000; t++) { const panel: [number, number][][] = [] for (let m = pick(1, 4); m > 0; m--) { const blocks: [number, number][] = [] for (let k = pick(0, 5); k > 0; k--) { const s = pick(0, 90) blocks.push([s, s + pick(1, 25)]) } panel.push(blocks) } const a = JSON.stringify(commonFree(panel, 0, 120)) const b = JSON.stringify(commonFreePooled(panel, 0, 120)) if (a !== b) differ++ } console.log(`3000 random panels, ${differ} differences`)
Fold against pool on random panels
3000 random panels, 0 differences
Output of one run
Related on LeetCode: Interval List Intersections and Employee Free Time (premium).
In the intersection loop, which pointer moves after recording an overlap, and why?
- The one whose range ends first.
- Later ranges in the other list start no earlier than that list's current range ends, so none of them can overlap the range that is finished.
Why does intersect test start < end before recording a range?
Part 5 · How many rooms a conference day needs
The problem
A conference has talks with fixed start and end times and each talk needs a room. The organisers want the fewest rooms that fit the whole day. Two talks can share a room when one ends no later than the other starts.
The answer equals the maximum number of talks running at the same moment. If five talks run at once you need five rooms. You never need more than the peak: when a talk starts, at most the peak minus one other talks are running, so one of the peak's rooms is free for it. Two methods compute the peak.
- Sweep. The events method from the first lesson, with ends before starts at equal times.
- Heap. Sort talks by start. Keep a min-heap of the end times of rooms in use. For each talk, if the earliest end in the heap is at or before this talk's start, that room is free, so pop it. Then push this talk's end. The heap's final size is the number of rooms.
A min-heap is a structure where the smallest item is always on top and push and pop cost O(log n). JavaScript has none built in. The class below is a copy of the heap built and explained in the two heaps chapter, shown here so the file runs on its own.
export class Heap<T> { items: T[] = [] less: (a: T, b: T) => boolean constructor(less: (a: T, b: T) => boolean) { this.less = less } get size(): number { return this.items.length } peek(): T | undefined { return this.items[0] } push(x: T): void { this.items.push(x) this.siftUp(this.items.length - 1) } siftUp(i: number): void { const a = this.items while (i > 0) { const p = (i - 1) >> 1 if (!this.less(a[i], a[p])) return ;[a[i], a[p]] = [a[p], a[i]] i = p } }
The heap class, first half
pop(): T | undefined { const a = this.items if (a.length === 0) return undefined const top = a[0] const last = a.pop() as T if (a.length > 0) { a[0] = last this.siftDown(0) } return top } siftDown(i: number): void { const a = this.items for (;;) { let m = i const l = 2 * i + 1 const r = l + 1 if (l < a.length && this.less(a[l], a[m])) m = l if (r < a.length && this.less(a[r], a[m])) m = r if (m === i) return ;[a[i], a[m]] = [a[m], a[i]] i = m } } }
The heap class, second half
Both methods in code
import { Heap } from './heap.ts' import { peakOverlap } from './sweep.ts' type Talk = [number, number] // Rooms needed = the most talks running at once (ends before starts). export function roomsSweep(talks: Talk[]): number { return peakOverlap(talks, true) } // Keep the end time of every busy room; reuse a room that has freed up. export function roomsHeap(talks: Talk[]): number { const byStart = talks.toSorted((a, b) => a[0] - b[0]) const ends = new Heap<number>((a, b) => a < b) for (const [start, end] of byStart) { if (ends.size > 0 && (ends.peek() as number) <= start) ends.pop() ends.push(end) } return ends.size }
Sweep and heap, side by side
In the heap version the pop and push together reuse a room: the freed room's old end is replaced by the new talk's end. The <= in the check is the half-open rule again, so a talk may start in the minute another ends.
import test from 'node:test' import assert from 'node:assert/strict' import { roomsSweep, roomsHeap } from './rooms.ts' type Talks = [number, number][] const both = (t: Talks) => [roomsSweep(t), roomsHeap(t)] test('back-to-back talks share one room', () => { assert.deepEqual(both([[540, 600], [600, 660], [660, 720]]), [1, 1]) }) test('identical talks each need a room', () => { assert.deepEqual(both([[540, 600], [540, 600], [540, 600]]), [3, 3]) }) test('a talk inside another needs its own room', () => { assert.deepEqual(both([[540, 720], [600, 630]]), [2, 2]) }) test('no talks, no rooms', () => { assert.deepEqual(both([]), [0, 0]) }) test('unsorted input gives the same answer', () => { assert.deepEqual(both([[660, 720], [540, 600], [570, 700]]), [2, 2]) })
Back-to-back, identical, nested, empty and unsorted input
✔ back-to-back talks share one room (1.0991ms) ✔ identical talks each need a room (0.1687ms) ✔ a talk inside another needs its own room (0.1245ms) ✔ no talks, no rooms (0.0835ms) ✔ unsorted input gives the same answer (0.149ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
Output of one run; the times in brackets vary
The scene draws the sweep on ten events from five talks given in hours. Pay attention to the moments where one talk ends and another starts.
Do they agree
import { mulberry32 } from './rng.ts' import { roomsSweep, roomsHeap } from './rooms.ts' const day: [number, number][] = [ [540, 600], [555, 615], [600, 660], [610, 690], [630, 700], [660, 720], [700, 760], [705, 765], [720, 780], ] console.log('sweep:', roomsSweep(day), 'heap:', roomsHeap(day)) const rand = mulberry32(99) const pick = (lo: number, hi: number) => lo + Math.floor(rand() * (hi - lo + 1)) let differ = 0 for (let t = 0; t < 4000; t++) { const talks: [number, number][] = [] for (let k = pick(0, 12); k > 0; k--) { const s = pick(0, 60) talks.push([s, s + pick(1, 20)]) } if (roomsSweep(talks) !== roomsHeap(talks)) differ++ } console.log(`4000 random days, ${differ} differences`)
A nine-talk day, then four thousand random days
sweep: 3 heap: 3 4000 random days, 0 differences
Output of one run
Both methods return 3 for the nine-talk day and never differ on the random days. Time is O(n log n) for both. The sweep stores 2n events; the heap stores at most one end time per room in use, so it needs less memory when rooms are few.
Which one should you reach for? The sweep answers only "how many". It is the simplest to get right and extends to weighted versions, such as the most passengers in a vehicle at once, where each start adds a number other than 1. The heap version can also tell you which room each talk uses if you keep room numbers next to the end times, which the sweep cannot do. The two heaps chapter builds on that idea, giving each build the lowest-numbered free machine.
One more detail about the heap method: it sorts by start and never needs to sort by end, because the heap does that work. After sorting, each talk either reuses the room that frees up first or opens a new one. If even the earliest-ending room is still busy, every room is busy, so no room can be reused and a new one is the only choice. That argument is why checking only the top of the heap is enough.
Related on LeetCode: Meeting Rooms II (premium) and Car Pooling.
What is the answer to "fewest rooms" in terms of the schedule?
- The most talks running at the same moment.
Part 6 · Cancel the fewest bookings
The problem
A hall receives bookings, each with a start and end, and some overlap. The manager wants to cancel as few bookings as possible so that no two remaining ones overlap. Equivalently: keep the largest set of bookings with no overlap.
This is a greedy problem: build the answer by repeatedly making the choice that looks best right now, and never revisit it. The skill is knowing which choice is safe. Three natural rules are to keep the shortest booking, the one that starts first, or the one that ends first. Only one of them is always right: keep the booking that ends first, drop everything that overlaps it, and repeat on what remains.
The run below shows why the other two rules fail. On the first day a long booking from 8 to 20 starts first and blocks three short ones. On the second a short booking sits between two longer ones that do not overlap each other, and taking the shortest blocks both.
import { keepMost } from './cancel-fewest.ts' type Booking = [number, number] // Greedy: take bookings in the order given, skipping any that overlap. function keepInOrder(order: Booking[]): number { const kept: Booking[] = [] for (const b of order) { if (kept.every((k) => b[0] >= k[1] || k[0] >= b[1])) kept.push(b) } return kept.length } const byStart = (x: Booking, y: Booking) => x[0] - y[0] const byLength = (x: Booking, y: Booking) => x[1] - x[0] - (y[1] - y[0]) const long: Booking[] = [[8, 20], [9, 11], [12, 14], [15, 17]] console.log('long booking first day') const a = keepInOrder(long.toSorted(byStart)) console.log(' earliest start first:', a) console.log(' earliest end first: ', keepMost(long).length) const mid: Booking[] = [[1, 5], [4, 6], [5, 9]] console.log('short booking in the middle') const b = keepInOrder(mid.toSorted(byLength)) console.log(' shortest first: ', b) console.log(' earliest end first: ', keepMost(mid).length)
Two rules on the same day of bookings
long booking first day earliest start first: 1 earliest end first: 3 short booking in the middle shortest first: 1 earliest end first: 2
Output of one run
Keeping the earliest start keeps one booking where the earliest end keeps three, and keeping the shortest keeps one where the earliest end keeps two.
Why earliest end is safe
The proof is an exchange argument. Take any best solution and let f be the booking in it that ends first. Let g be the booking that ends first overall, so g ends no later than f. Every other booking in the solution starts at or after f ends, so at or after g ends, and none of them overlaps g. Swapping g in for f gives a solution that is still valid and has the same size, so some best solution contains g. Every booking that does not overlap g starts at or after g ends, because none ends before g does. The rest of that best solution is a choice among those later bookings, so what is left is the same problem, and the same argument picks its earliest-ending booking next. Each step is safe, so the whole sequence is optimal.
The code and the check
type Booking = [number, number] // Keep the booking that ends first, drop whatever overlaps it, repeat. export function keepMost(bookings: Booking[]): Booking[] { const byEnd = bookings.toSorted((a, b) => a[1] - b[1]) const kept: Booking[] = [] let lastEnd = -Infinity for (const b of byEnd) { if (b[0] >= lastEnd) { kept.push(b) lastEnd = b[1] } } return kept } export function fewestCancellations(bookings: Booking[]): number { return bookings.length - keepMost(bookings).length }
Keep the booking that ends first, then count what was dropped
Sorting by end costs O(n log n), and the pass is O(n). The condition b[0] >= lastEnd allows back-to-back bookings, again the half-open rule.
import test from 'node:test' import assert from 'node:assert/strict' import { keepMost, fewestCancellations } from './cancel-fewest.ts' test('back-to-back bookings all stay', () => { assert.equal(fewestCancellations([[1, 3], [3, 5], [5, 8]]), 0) }) test('a booking covering three short ones is the one to drop', () => { const day: [number, number][] = [[0, 10], [1, 3], [4, 6], [7, 9]] assert.equal(fewestCancellations(day), 1) }) test('identical bookings keep only one', () => { const four: [number, number][] = [[3, 7], [3, 7], [3, 7], [3, 7]] assert.equal(fewestCancellations(four), 3) }) test('the kept bookings are sorted by end and do not overlap', () => { const kept = keepMost([[5, 9], [1, 4], [3, 6], [8, 12], [4, 5]]) assert.deepEqual(kept, [[1, 4], [4, 5], [5, 9]]) }) test('no bookings, no cancellations', () => { assert.equal(fewestCancellations([]), 0) })
Tests for chains, a covering booking, duplicates and empty input
✔ back-to-back bookings all stay (1.0835ms) ✔ a booking covering three short ones is the one to drop (0.1066ms) ✔ identical bookings keep only one (0.0737ms) ✔ the kept bookings are sorted by end and do not overlap (0.525ms) ✔ no bookings, no cancellations (0.0969ms) ℹ tests 5 ℹ pass 5 ℹ fail 0
Output of one run; the times in brackets vary
Tests can miss a wrong rule, so the last check is brute force. For up to 12 bookings there are at most 4,096 subsets, and the program tries every one, keeping the largest set with no overlap.
import { mulberry32 } from './rng.ts' import { keepMost } from './cancel-fewest.ts' type Booking = [number, number] // Try every subset: the largest one with no two bookings overlapping. function bruteMost(bookings: Booking[]): number { const n = bookings.length let best = 0 for (let mask = 0; mask < 1 << n; mask++) { const chosen = bookings.filter((_, i) => mask & (1 << i)) chosen.sort((a, b) => a[0] - b[0]) let ok = true for (let i = 1; i < chosen.length && ok; i++) { if (chosen[i][0] < chosen[i - 1][1]) ok = false } if (ok) best = Math.max(best, chosen.length) } return best }
Brute force: try every subset
Variations
Two variations use the same sorted pass. To list which bookings to cancel, collect the ones the loop skips rather than counting them. To weigh bookings by revenue, the greedy rule no longer works, since a short booking may earn less than a long one that blocks it, and you need dynamic programming. A related cleanup, dropping every booking that lies completely inside another, sorts by start (longer first on equal starts) and keeps a running maximum end.
Related on LeetCode: Non-overlapping Intervals and Remove Covered Intervals.
Which rule keeps the most non-overlapping bookings: earliest start, shortest, or earliest end?
- Earliest end.
- The other two have counterexamples, such as a long early booking that blocks three short ones.
In one sentence, why is keeping the earliest-ending booking safe?
- Swapping it for the first booking of any best solution keeps that solution valid and the same size.
For bookings [2, 6], [3, 4], [5, 9] and [6, 8], which does the earliest-end rule keep, and how many are cancelled?
- It keeps [3, 4] and [6, 8], so two are cancelled.
- By end time: [3, 4] is kept, [2, 6] starts before 4, [6, 8] starts at or after 4 and is kept, and [5, 9] starts before 8.
All chapters · Previous: Sliding Windows: Fixed and Variable Ranges Over Sequences