Lesson 2 · Unit 04
Intervals: merge and schedule
Sort first, then one greedy pass
What you practise
- Sort by start to merge
- Sort by end to keep the most
Try a question from this lesson
Pick one
A room is booked from 1 to 4 and from 3 to 6. The two bookings overlap. Merged into one block, what time does it cover?
Correct answer
1 to 6
Why
The merged block starts at the earlier start and ends at the later end: 1 to 6. The stretch from 3 to 4 is only the part they share.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Merge overlapping spans
Sort the spans by start. Then walk them once, keeping a list of merged blocks.
If a span starts at or before the end of the last block, it overlaps: stretch that block's end if needed. Otherwise it starts a new block. Sorting is what makes it enough to look at the last block only.
def merge(spans):
spans.sort()
out = [spans[0]]
for s, e in spans[1:]:
last = out[-1]
if s <= last[1]:
last[1] = max(last[1], e)
else:
out.append([s, e])
return outfunction merge(spans) {
spans.sort((a, b) => a[0] - b[0]);
const out = [spans[0]];
for (const [s, e] of spans.slice(1)) {
const last = out[out.length - 1];
if (s <= last[1]) {
last[1] = Math.max(last[1], e);
} else {
out.push([s, e]);
}
}
return out;
}function merge(spans: number[][]) {
spans.sort((a, b) => a[0] - b[0]);
const out = [spans[0]];
for (const [s, e] of spans.slice(1)) {
const last = out[out.length - 1];
if (s <= last[1]) {
last[1] = Math.max(last[1], e);
} else {
out.push([s, e]);
}
}
return out;
}Python notespans.sort() compares lists item by item, so it orders by start and breaks ties by end. No key function is needed.
JavaScript noteWithout a compare function, sort() compares items as text, so a span starting at 10 would land before one starting at 2.
TypeScript notenumber[][] is a list of lists of numbers. A stricter choice for a pair is the tuple type [number, number], which also fixes the length at 2.
Concept
The most meetings in one room
Many meetings want the same room. To hold as many as possible, sort them by END time and take each one that starts once the room is free.
This is a greedy algorithm: it makes the choice that looks best now and never undoes it. Ending earliest is safe because it leaves the most time for everything else.
def max_meetings(spans):
spans.sort(key=lambda sp: sp[1])
count = 0
free_at = float('-inf')
for start, end in spans:
if start >= free_at:
count += 1
free_at = end
return countfunction maxMeetings(spans) {
spans.sort((a, b) => a[1] - b[1]);
let count = 0;
let freeAt = -Infinity;
for (const [start, end] of spans) {
if (start >= freeAt) {
count += 1;
freeAt = end;
}
}
return count;
}function maxMeetings(spans: number[][]) {
spans.sort((a, b) => a[1] - b[1]);
let count = 0;
let freeAt = -Infinity;
for (const [start, end] of spans) {
if (start >= freeAt) {
count += 1;
freeAt = end;
}
}
return count;
}Python notekey=lambda sp: sp[1] sorts by each span's end. float('-inf') is smaller than every number, so the first meeting always fits.
JavaScript note(a, b) => a[1] - b[1] sorts by the second item of each pair, the end time. -Infinity is smaller than every number.
TypeScript notefor (const [start, end] of spans) unpacks each inner array into two variables, both typed number.
10 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 2× fill the blanks
- 1× match the pairs
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.