Merge, insert and schedule intervals after sorting by start.
Use it when events have a start and an end. You may need to join them, add one, count how many run at once, or find the time two lists share. Signal words: overlap, join, free time, at the same time, double booked, add a booking.
Start sort by start, unless the list is already sorted. Say which ends count.
Step compare the next slot with the end of the open block. Join it, or start a new block.
Stop when the list is used up. For two lists, stop when one of them is used up.
It does not pick the most events that fit together. That needs a sort by end time.
Cost: O(n log n) for the sort, and O(n) for one scan. Insert and intersect read sorted lists, so they cost O(n + m).
In this lesson you merge overlapping events after sorting them by start, and you say exactly which ends count. You add one event to a sorted calendar in a single pass. You count the most events at one time with a sweep, and you intersect two sorted lists of free time. Each method comes with a traced run.
You work on a calendar app. A day is split into numbered slots of 15 minutes. An event covers the slots from its start number to its end number, and both ends count. Events arrive in any order, and many of them overlap.
Your team lead says: Show each day as joined busy blocks. One block must replace every run of events that share a slot.
Here is a short test: seven events, as slot numbers: [9, 12], [1, 3], [10, 14], [2, 6], [16, 18], [15, 17] and [8, 9]. The blocks are [1, 6], [8, 14] and [15, 18].
So the task is this: join the events into blocks, and keep it fast for a user who holds 100,000 events.
You lay strips of tape on a ruler, each from one number to another. Where two strips cover a common number, they fuse into one band.
If you lay the strips from left to right, you only look at the last band. Either the next strip reaches it, or it starts past its end and begins a new band. The tape is the event, the ruler is the slot numbers, and the band is the block.
Strips of tape on a ruler: strips that share a number fuse into one band, and you only watch the last band.
Before you write code, join the seven events on a ruler. It shows what a block is.
Solve it by hand: Seven events: sort by start, then join. The hand-solve sheet loads in your browser.
You put the events in order of start. You keep one open block, and you check each event against its end.
The events are [9, 12], [1, 3], [10, 14], [2, 6], [16, 18], [15, 17] and [8, 9]. Sorted by start, they read [1, 3], [2, 6], [8, 9], [9, 12], [10, 14], [15, 17], [16, 18].
| Event | Starts at or before the block's end? | Blocks after it |
|---|---|---|
| [1, 3] | no block yet | [1, 3] |
| [2, 6] | 2 is at most 3: joins, end becomes 6 | [1, 6] |
| [8, 9] | 8 is after 6: new block | [1, 6] [8, 9] |
| [9, 12] | 9 is at most 9: joins, end becomes 12 | [1, 6] [8, 12] |
| [10, 14] | 10 is at most 12: joins, end becomes 14 | [1, 6] [8, 14] |
| [15, 17] | 15 is after 14: new block | [1, 6] [8, 14] [15, 17] |
| [16, 18] | 16 is at most 17: joins, end becomes 18 | [1, 6] [8, 14] [15, 18] |
The calendar shows three blocks: [1, 6], [8, 14] and [15, 18].
On paper you see the overlaps with your eyes. A program has no eyes, so the first attempt tests pairs. It joins any two events that share a slot, and it repeats until nothing joins.
def merge_intervals(slots):
blocks = [list(slot) for slot in slots]
joined = True
while joined:
joined = False
i = 0
while i < len(blocks):
j = i + 1
while j < len(blocks):
if blocks[j][0] <= blocks[i][1] and blocks[i][0] <= blocks[j][1]:
blocks[i] = [min(blocks[i][0], blocks[j][0]), max(blocks[i][1], blocks[j][1])]
del blocks[j]
joined = True
else:
j += 1
i += 1
return sorted(blocks)This is correct. On the seven test events it returns the three blocks after 13 pair tests.
Now check the real size. A busy user holds 100,000 events, and one pair test takes 1 microsecond.
The calendar has 100,000 events, and every refresh joins them again.
Here is the count:
So the first attempt is far too slow at real size.
Predict the cost
Q One pass tests every pair of events once. For 2,000 events, how many pair tests is that?
Answer: C
A pair is two different events, and each pair is tested once. The count is n × (n − 1) / 2, so 1,999,000. The repeated passes of the first attempt made 2,288,454.
The first attempt is correct. Its cost comes from not using the order of the events.
Sort the events by start, and look at the order. Take the open block, the last one you built. The next event starts at or after the start of every event before it.
If it starts after the block's end, it cannot join this block. Every event after it starts even later, so no later event can join this block either. The block is final.
If it starts at or before the block's end, it joins. You never look back at older blocks, and you never test two old events again.
Race: Two ways to merge events. The operation counter loads in your browser.
The race counts every test. At 1,000 events the pair version made 599,513 tests, and sort-then-scan made 9,608. At 2,000 events the counts are 2,288,454 and 21,264.
The merge scan: sorted by start, each event joins the open block when it starts at or before its end, and the block keeps the larger end.
Before you code, decide which ends count. A calendar of slot numbers, as in this lesson, counts both ends. A calendar of minutes usually counts the start and not the end, so a meeting that ends at 10 leaves minute 10 free.
| Pair | Ends that count | Share a slot or minute? | Overlap? |
|---|---|---|---|
| [1, 3] and [3, 5] | both | slot 3 | yes: they join |
| [1, 3] and [4, 6] | both | none: they sit side by side | no |
| [9, 10) and [10, 11) | start only | none: they touch | no |
| [9, 11) and [10, 12) | start only | minute 10 | yes |
Here are the two tests. With both ends counted, two ranges overlap when the later start is at most the earlier end. With the end excluded, they overlap when the later start is less than the earlier end. A check of every pair of ranges inside 0 to 5 confirmed both tests.
Touching ranges, such as [9, 10) and [10, 11), do not overlap. Whether the calendar still shows them as one block is a choice of the product. Read the statement and follow it. This lesson uses slot numbers for merging and minutes with the end excluded for meetings.
The events are [3, 9], [12, 14], [1, 4], [5, 6], [13, 20], [22, 25], [24, 26] and [19, 21]. You merge them with the scan, and the player stops at five steps and asks you to predict.
Dry run: Predict the block's end: eight events. The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Sorted event | Starts at or before the block's end? | Block after it |
|---|---|---|
| [1, 4] | first block | [1, 4] |
| [3, 9] | yes | [1, 9] |
| [5, 6] | yes, and it ends inside the block | [1, 9] |
| [12, 14] | no | [1, 9] [12, 14] |
| [13, 20] | yes | [1, 9] [12, 20] |
| [19, 21] | yes | [1, 9] [12, 21] |
| [22, 25] | no | [1, 9] [12, 21] [22, 25] |
| [24, 26] | yes | [1, 9] [12, 21] [22, 26] |
The calendar shows three blocks. Look at the event [5, 6]. It joins the block [1, 9], but its end 6 is smaller than 9, so the block keeps 9. Taking the larger end is the key line of the code.
Predict the join
Q Two events are [2, 5] and [5, 8], as slot numbers with both ends counted. What does the merge return?
Answer: B
The later start is 5 and the earlier end is 5. Five is at most five, so the two events share slot 5 and join into [2, 8].
The sort costs n log n. The scan costs one test for each event. Together they are O(n log n), and the scan alone is O(n).
Here is the rule that keeps the merge correct. Every line of the templates protects it.
After sorting by start, the open block is the union of the slots that reach it, and no later slot can join an earlier block.
During the scan, all blocks before the open block are final. Their ends are less than the start of the next block, and every later slot starts at least as late as the current one. So a later slot cannot reach them.
That is why one pass is enough. The scan keeps one open block and compares each slot with its end only.
Use it when events have a start and an end. You may need to join them, add one, count how many run at once, or find the time two lists share. Signal words: overlap, join, free time, at the same time, double booked, add a booking.
Start: sort by start, unless the list is already sorted. Say which ends count.
Step: compare the next slot with the end of the open block. Join it, or start a new block.
Stop: when the list is used up. For two lists, stop when one of them is used up.
It does not pick the most events that fit together. That needs a sort by end time.
Cost: O(n log n) for the sort, and O(n) for one scan. Insert and intersect read sorted lists, so they cost O(n + m).
def merge_intervals(slots):
# [1] Sort by start, so every slot that can join the open block comes right after it.
ordered = sorted(slots)
merged = []
for start, end in ordered:
if merged and start <= merged[-1][1]:
# [2] A slot that starts at or before the open block's end shares a slot with it: it joins, and the block keeps the larger end.
merged[-1][1] = max(merged[-1][1], end)
else:
# [3] Otherwise the slot starts a new block.
merged.append([start, end])
# [4] Return the blocks, sorted by start.
return mergedpublic int[][] mergeIntervals(int[][] slots) {
// [1] Sort by start, so every slot that can join the open block comes right after it.
int[][] ordered = slots.clone();
Arrays.sort(ordered, (a, b) -> Integer.compare(a[0], b[0]));
List<int[]> merged = new ArrayList<>();
for (int[] slot : ordered) {
if (!merged.isEmpty() && slot[0] <= merged.get(merged.size() - 1)[1]) {
// [2] A slot that starts at or before the open block's end shares a slot with it: it joins, and the block keeps the larger end.
int[] open = merged.get(merged.size() - 1);
open[1] = Math.max(open[1], slot[1]);
} else {
// [3] Otherwise the slot starts a new block.
merged.add(new int[] {slot[0], slot[1]});
}
}
// [4] Return the blocks, sorted by start.
return merged.toArray(new int[0][]);
}vector<vector<int>> mergeIntervals(const vector<vector<int>>& slots) {
// [1] Sort by start, so every slot that can join the open block comes right after it.
vector<vector<int>> ordered = slots;
sort(ordered.begin(), ordered.end());
vector<vector<int>> merged;
for (const auto& slot : ordered) {
if (!merged.empty() && slot[0] <= merged.back()[1]) {
// [2] A slot that starts at or before the open block's end shares a slot with it: it joins, and the block keeps the larger end.
merged.back()[1] = max(merged.back()[1], slot[1]);
} else {
// [3] Otherwise the slot starts a new block.
merged.push_back({slot[0], slot[1]});
}
}
// [4] Return the blocks, sorted by start.
return merged;
}function mergeIntervals(slots) {
// [1] Sort by start, so every slot that can join the open block comes right after it.
const ordered = [...slots].sort((a, b) => a[0] - b[0]);
const merged = [];
for (const [start, end] of ordered) {
if (merged.length > 0 && start <= merged[merged.length - 1][1]) {
// [2] A slot that starts at or before the open block's end shares a slot with it: it joins, and the block keeps the larger end.
merged[merged.length - 1][1] = Math.max(merged[merged.length - 1][1], end);
} else {
// [3] Otherwise the slot starts a new block.
merged.push([start, end]);
}
}
// [4] Return the blocks, sorted by start.
return merged;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Break it: Find the events this merge splits wrongly. This merge sorts the events by their end, not their start, and then joins as usual. Both ends count. Find a list of events where it gives the wrong blocks.
def merge_intervals(slots):
ordered = sorted(slots, key=lambda slot: slot[1])
merged = []
for start, end in ordered:
if merged and start <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], end)
else:
merged.append([start, end])
return mergedThe traced run in Struggle used this template on the seven events. The scan reads 7 events and returns [[1, 6], [8, 14], [15, 18]].
The calendar is already sorted, and no two events in it share a slot. You add one event. The new event may reach many events, so no sort is needed. You split the calendar into three parts.
def insert_slot(slots, new_slot):
start, end = new_slot
result = []
i = 0
n = len(slots)
# [1] Copy every slot that ends before the new slot starts: it shares no slot with it.
while i < n and slots[i][1] < start:
result.append(slots[i])
i += 1
# [2] Absorb every slot that starts at or before the new slot's end: the new slot grows to cover it.
while i < n and slots[i][0] <= end:
start = min(start, slots[i][0])
end = max(end, slots[i][1])
i += 1
# [3] Place the grown slot, then copy every slot that starts after it.
result.append([start, end])
while i < n:
result.append(slots[i])
i += 1
# [4] Return the new calendar.
return resultpublic int[][] insertSlot(int[][] slots, int[] newSlot) {
int start = newSlot[0];
int end = newSlot[1];
List<int[]> result = new ArrayList<>();
int i = 0;
int n = slots.length;
// [1] Copy every slot that ends before the new slot starts: it shares no slot with it.
while (i < n && slots[i][1] < start) {
result.add(slots[i]);
i++;
}
// [2] Absorb every slot that starts at or before the new slot's end: the new slot grows to cover it.
while (i < n && slots[i][0] <= end) {
start = Math.min(start, slots[i][0]);
end = Math.max(end, slots[i][1]);
i++;
}
// [3] Place the grown slot, then copy every slot that starts after it.
result.add(new int[] {start, end});
while (i < n) {
result.add(slots[i]);
i++;
}
// [4] Return the new calendar.
return result.toArray(new int[0][]);
}vector<vector<int>> insertSlot(const vector<vector<int>>& slots, const vector<int>& newSlot) {
int start = newSlot[0];
int end = newSlot[1];
vector<vector<int>> result;
size_t i = 0;
size_t n = slots.size();
// [1] Copy every slot that ends before the new slot starts: it shares no slot with it.
while (i < n && slots[i][1] < start) {
result.push_back(slots[i]);
i++;
}
// [2] Absorb every slot that starts at or before the new slot's end: the new slot grows to cover it.
while (i < n && slots[i][0] <= end) {
start = min(start, slots[i][0]);
end = max(end, slots[i][1]);
i++;
}
// [3] Place the grown slot, then copy every slot that starts after it.
result.push_back({start, end});
while (i < n) {
result.push_back(slots[i]);
i++;
}
// [4] Return the new calendar.
return result;
}function insertSlot(slots, newSlot) {
let [start, end] = newSlot;
const result = [];
let i = 0;
const n = slots.length;
// [1] Copy every slot that ends before the new slot starts: it shares no slot with it.
while (i < n && slots[i][1] < start) {
result.push(slots[i]);
i++;
}
// [2] Absorb every slot that starts at or before the new slot's end: the new slot grows to cover it.
while (i < n && slots[i][0] <= end) {
start = Math.min(start, slots[i][0]);
end = Math.max(end, slots[i][1]);
i++;
}
// [3] Place the grown slot, then copy every slot that starts after it.
result.push([start, end]);
while (i < n) {
result.push(slots[i]);
i++;
}
// [4] Return the new calendar.
return result;
}The calendar is [1, 3], [6, 8], [10, 12], [15, 17] and [20, 22]. The new event is [7, 16].
Dry run: Add one event to a sorted calendar. The step-by-step player loads in your browser.
| Event | Phase | The new event after it |
|---|---|---|
| [1, 3] | copy: it ends at 3, before 7 | [7, 16] |
| [6, 8] | absorb: it starts at 6, at most 16 | [6, 16] |
| [10, 12] | absorb: it starts at 10 | [6, 16] |
| [15, 17] | absorb: it starts at 15, and it ends at 17 | [6, 17] |
| [20, 22] | copy: it starts after 17 | [6, 17] |
The result is [1, 3], [6, 17] and [20, 22]. The scan reads each event once, so it costs O(n).
Insert one event into a sorted calendar in three phases: copy what ends before it, absorb what reaches it, copy the rest.
Exercise · Predict the output: What does the new event swallow?. The calendar holds [1, 3], [5, 7] and [9, 11], as slot numbers with both ends counted. The code inserts the event [4, 9]. What does it print?
slots = [[1, 3], [5, 7], [9, 11]]
start, end = 4, 9
result = []
i = 0
n = len(slots)
while i < n and slots[i][1] < start:
result.append(slots[i])
i += 1
while i < n and slots[i][0] <= end:
start = min(start, slots[i][0])
end = max(end, slots[i][1])
i += 1
result.append([start, end])
while i < n:
result.append(slots[i])
i += 1
print(" ".join(f"{a}-{b}" for a, b in result))A meeting is a half-open range of minutes: it starts at its first minute and ends at its end minute, which is free. You want the most meetings at one time, which is the number of rooms.
Turn every meeting into two events: +1 at its start and -1 at its end. Sort the events by time. When an end and a start have the same time, the end goes first, because the room is free again at that minute.
def most_at_once(meetings):
# [1] Make two events for every meeting: +1 when it starts, -1 when it ends.
events = []
for start, end in meetings:
events.append((start, 1))
events.append((end, -1))
# [2] Sort by time. At the same time an end (-1) comes before a start (+1), because the end minute is free.
events.sort()
busy = 0
most = 0
for time, change in events:
# [3] Apply the event and keep the largest count seen.
busy += change
most = max(most, busy)
# [4] The largest count is the number of rooms needed.
return mostpublic int mostAtOnce(int[][] meetings) {
// [1] Make two events for every meeting: +1 when it starts, -1 when it ends.
int[][] events = new int[meetings.length * 2][];
int k = 0;
for (int[] meeting : meetings) {
events[k++] = new int[] {meeting[0], 1};
events[k++] = new int[] {meeting[1], -1};
}
// [2] Sort by time. At the same time an end (-1) comes before a start (+1), because the end minute is free.
Arrays.sort(events, (a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0]) : Integer.compare(a[1], b[1]));
int busy = 0;
int most = 0;
for (int[] event : events) {
// [3] Apply the event and keep the largest count seen.
busy += event[1];
most = Math.max(most, busy);
}
// [4] The largest count is the number of rooms needed.
return most;
}int mostAtOnce(const vector<vector<int>>& meetings) {
// [1] Make two events for every meeting: +1 when it starts, -1 when it ends.
vector<pair<int, int>> events;
for (const auto& meeting : meetings) {
events.push_back({meeting[0], 1});
events.push_back({meeting[1], -1});
}
// [2] Sort by time. At the same time an end (-1) comes before a start (+1), because the end minute is free.
sort(events.begin(), events.end());
int busy = 0;
int most = 0;
for (const auto& event : events) {
// [3] Apply the event and keep the largest count seen.
busy += event.second;
most = max(most, busy);
}
// [4] The largest count is the number of rooms needed.
return most;
}function mostAtOnce(meetings) {
// [1] Make two events for every meeting: +1 when it starts, -1 when it ends.
const events = [];
for (const [start, end] of meetings) {
events.push([start, 1]);
events.push([end, -1]);
}
// [2] Sort by time. At the same time an end (-1) comes before a start (+1), because the end minute is free.
events.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
let busy = 0;
let most = 0;
for (const [time, change] of events) {
// [3] Apply the event and keep the largest count seen.
busy += change;
most = Math.max(most, busy);
}
// [4] The largest count is the number of rooms needed.
return most;
}The meetings are [9, 12], [10, 11], [11, 14], [13, 15], [9, 10] and [10, 13].
Dry run: Six meetings as events. The step-by-step player loads in your browser.
| Sorted event | Meetings running after it | Largest so far |
|---|---|---|
| 9: +1 | 1 | 1 |
| 9: +1 | 2 | 2 |
| 10: -1 | 1 | 2 |
| 10: +1 | 2 | 2 |
| 10: +1 | 3 | 3 |
| 11: -1 | 2 | 3 |
| 11: +1 | 3 | 3 |
| 12: -1 | 2 | 3 |
| 13: -1 | 1 | 3 |
| 13: +1 | 2 | 3 |
| 14: -1 | 1 | 3 |
| 15: -1 | 0 | 3 |
The most meetings at one time is 3, so three rooms are needed. The sort of the 12 events dominates, so the cost is O(n log n).
A heap gives another way to the same answer. Sort the meetings by start and keep a min-heap of the end times of the running meetings. A meeting that starts at or after the smallest end reuses that room. On these six meetings the heap also ends with 3.
The heap pattern for pools of rooms and servers is taught in Scheduling with heaps. The sweep needs no heap.
The sweep counts meetings with plus one at each start and minus one at each end, and at the same minute the end comes first.
If the slots are slot numbers with both ends counted, use the end plus one as the -1 time. Then [1, 3] and [3, 5] become [1, 4) and [3, 6), and they overlap at slot 3.
Two people each hold a sorted list of free slots, with no overlaps inside a list. You want the slots where both are free. Take one index on each list.
def shared_slots(first, second):
result = []
i = 0
j = 0
# [1] Walk both lists with one index each. Each list is sorted and has no overlaps inside it.
while i < len(first) and j < len(second):
# [2] The shared part starts at the later start and ends at the earlier end.
low = max(first[i][0], second[j][0])
high = min(first[i][1], second[j][1])
# [3] If low is at most high, the two slots share at least one slot number: record the shared part.
if low <= high:
result.append([low, high])
# [4] Drop the slot that ends first. It cannot meet anything later in the other list.
if first[i][1] < second[j][1]:
i += 1
else:
j += 1
return resultpublic int[][] sharedSlots(int[][] first, int[][] second) {
List<int[]> result = new ArrayList<>();
int i = 0;
int j = 0;
// [1] Walk both lists with one index each. Each list is sorted and has no overlaps inside it.
while (i < first.length && j < second.length) {
// [2] The shared part starts at the later start and ends at the earlier end.
int low = Math.max(first[i][0], second[j][0]);
int high = Math.min(first[i][1], second[j][1]);
// [3] If low is at most high, the two slots share at least one slot number: record the shared part.
if (low <= high) {
result.add(new int[] {low, high});
}
// [4] Drop the slot that ends first. It cannot meet anything later in the other list.
if (first[i][1] < second[j][1]) {
i++;
} else {
j++;
}
}
return result.toArray(new int[0][]);
}vector<vector<int>> sharedSlots(const vector<vector<int>>& first, const vector<vector<int>>& second) {
vector<vector<int>> result;
size_t i = 0;
size_t j = 0;
// [1] Walk both lists with one index each. Each list is sorted and has no overlaps inside it.
while (i < first.size() && j < second.size()) {
// [2] The shared part starts at the later start and ends at the earlier end.
int low = max(first[i][0], second[j][0]);
int high = min(first[i][1], second[j][1]);
// [3] If low is at most high, the two slots share at least one slot number: record the shared part.
if (low <= high) {
result.push_back({low, high});
}
// [4] Drop the slot that ends first. It cannot meet anything later in the other list.
if (first[i][1] < second[j][1]) {
i++;
} else {
j++;
}
}
return result;
}function sharedSlots(first, second) {
const result = [];
let i = 0;
let j = 0;
// [1] Walk both lists with one index each. Each list is sorted and has no overlaps inside it.
while (i < first.length && j < second.length) {
// [2] The shared part starts at the later start and ends at the earlier end.
const low = Math.max(first[i][0], second[j][0]);
const high = Math.min(first[i][1], second[j][1]);
// [3] If low is at most high, the two slots share at least one slot number: record the shared part.
if (low <= high) {
result.push([low, high]);
}
// [4] Drop the slot that ends first. It cannot meet anything later in the other list.
if (first[i][1] < second[j][1]) {
i++;
} else {
j++;
}
}
return result;
}Anna is free at [0, 3], [5, 9], [12, 20] and [25, 30]. Ben is free at [2, 6], [8, 13], [14, 16] and [18, 27].
Dry run: Two people's free lists. The step-by-step player loads in your browser.
| Anna's slot | Ben's slot | Later start | Earlier end | Shared |
|---|---|---|---|---|
| [0, 3] | [2, 6] | 2 | 3 | [2, 3] |
| [5, 9] | [2, 6] | 5 | 6 | [5, 6] |
| [5, 9] | [8, 13] | 8 | 9 | [8, 9] |
| [12, 20] | [8, 13] | 12 | 13 | [12, 13] |
| [12, 20] | [14, 16] | 14 | 16 | [14, 16] |
| [12, 20] | [18, 27] | 18 | 20 | [18, 20] |
| [25, 30] | [18, 27] | 25 | 27 | [25, 27] |
After each pair, you drop the slot that ends first. The loop ends when one list is used up. Each step moves one index, so it costs O(n + m). The shared slots are [2, 3], [5, 6], [8, 9], [12, 13], [14, 16], [18, 20] and [25, 27].
Exercise · Find the bug: The slot that is dropped too soon. This finds the slots where two people are both free, but it loses some of them when one slot is long. Which line is wrong?
def shared_slots(first, second):
result = []
i = 0
j = 0
while i < len(first) and j < len(second):
low = max(first[i][0], second[j][0])
high = min(first[i][1], second[j][1])
if low <= high:
result.append([low, high])
if first[i][0] < second[j][0]:
i += 1
else:
j += 1
return resultThe four templates share one question: what does the order give you? You can answer it before you write code.
Then check the two ends: what do the templates do on an empty list, and on events that all sit inside one long event?
| Question | Use | Why |
|---|---|---|
| Show joined busy blocks | Merge | One scan after the sort |
| Add one event to a sorted calendar | Insert | No sort, one pass |
| How many rooms | Sweep | The largest running count |
| When are both people free | Intersect | Two indexes, no sort |
| Free time in one day | Merge, then read the gaps | The gaps lie between blocks |
The day has slots 0 to 20. The seven test events merge into [1, 6], [8, 14] and [15, 18]. The app wants the free slots.
Merge with Template 1. Then read the gaps between the blocks, and before the first and after the last.
| From | To | Free slots |
|---|---|---|
| start of the day | before [1, 6] | 0 to 0 |
| after [1, 6] | before [8, 14] | 7 to 7 |
| after [8, 14] | before [15, 18] | none: slot 14 is followed by slot 15 |
| after [15, 18] | end of the day | 19 to 20 |
The free slots are [0, 0], [7, 7] and [19, 20]. A run of the code gave the same list.
Real data brings edge cases.
For slots = [] the merge returns [], since the loop does not run. For meetings = [] the sweep returns 0.
For slots = [[2, 5], [2, 5], [2, 5]] every event starts at the open block's end or before, so the result is [[2, 5]].
For slots = [[0, 100], [1, 2], [3, 4]] the short events join the long one, and the block keeps the larger end. The result is [[0, 100]].
For slots = [[1, 3], [4, 6]] the events share no slot, so the result is [[1, 3], [4, 6]]. For slots = [[1, 3], [3, 5]] they share slot 3, and the result is [[1, 5]].
For slots = [[5, 6]] and new_slot = [1, 2] the first phase copies nothing, the second absorbs nothing, and the result is [[1, 2], [5, 6]].
This version scans the list in the order it arrives. It compares each event with the open block, as the template does, but it skips the sort.
Counterexample: slots = [[8, 10], [1, 3], [2, 6]] returns [[8, 10]]. The event [1, 3] starts before 10, so it joins the block [8, 10], and the block keeps its start 8. Slots 1 to 6 are lost. The correct result is [[1, 6], [8, 10]].
Sort by start first.
This version sets the block's end to the end of the new event, not to the larger end.
Counterexample: slots = [[1, 10], [2, 4], [5, 7]] returns [[1, 4], [5, 7]]. The event [2, 4] lowers the end to 4, so [5, 7] looks separate. The correct result is [[1, 10]].
Use max(end of block, end of event).
Keeping the last end instead of the larger end splits one block in two: one to ten, two to four, five to seven.
This version joins only when the later start is less than the earlier end. With slot numbers, that misses events that share exactly one slot.
Counterexample: slots = [[1, 3], [3, 5]] returns [[1, 3], [3, 5]]. Both events cover slot 3, so the correct result is [[1, 5]].
Match the test to the ends that count: at most for slot numbers, less than for minutes with the end excluded.
This version sorts the events by time and puts a start before an end at the same time. A room that frees at minute 5 then looks busy at minute 5.
Counterexample: meetings = [[0, 5], [5, 10]] returns 2, and one room is enough. On the six meetings of Template 3 it returns 4 instead of 3.
Sort so that -1 comes before +1 at the same time.
The app lets a user keep as many events as possible, and no two kept events may overlap. Take [1, 10], [2, 3] and [4, 5]. Sorting by start keeps [1, 10] first, and nothing else fits: 1 event. Sorting by end keeps [2, 3] and [4, 5]: 2 events.
Sorting by start serves merging. The choice problem needs the end time, and Sort, then choose in the greedy module proves why.
Your team lead brings four product changes. Each one asks what to do with the order.
The app only warns when a new event clashes with any other. Sort by start and compare each event with the one before it. If a start is before the previous end, there is a clash. The problem "Meeting time overlap check" practises it.
Exercise · Put it in order: Is there any clash?. Arrange the lines into a check that returns true when any two meetings clash. A meeting runs from its start minute up to, but not including, its end minute.
def has_clash(meetings):
ordered = sorted(meetings)
for i in range(1, len(ordered)):
if ordered[i][0] < ordered[i - 1][1]:
return True
return False
ordered = meetings
if ordered[i][0] <= ordered[i - 1][1]:A holiday blocks one range of slots. Walk the sorted free slots, keep the parts before and after the blackout, and drop the parts inside it. It is the three phases of the insert, in reverse. The problem "Carve a blackout out of the free slots" practises it.
A car-pool app has groups of different sizes. The sweep adds the group size at pick-up and subtracts it at drop-off, and it reports the first mark where the load passes the capacity. The problem "Car pool capacity check" practises it.
Several people have busy lists. Put all the busy slots into one list, merge it, and read the gaps that are long enough. The problem "Employee free time" practises it.
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you merge overlapping events, and which ends you count. Then say how many pair tests the first attempt makes for 2,000 events in one pass. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have counted it.
I sort the events by start and keep one open block. An event that starts at or before the block's end joins it, and the block keeps the larger end. I say first which ends count: both for slot numbers, and not the end for minutes. Testing every pair costs 1,999,000 tests for 2,000 events, while sorting costs n log n.
For intervals, I first sort by start. Then I keep one open block and scan once. If the next interval starts at or before the block's end, it joins, and the block keeps the larger end. Otherwise it starts a new block.
I state which ends count before I code. With both ends counted, a shared point means overlap. With the end excluded, touching ranges do not overlap.
To add one interval to a sorted list, I copy what ends before it, absorb what reaches it, and copy the rest. To count the most intervals at one time, I make a plus one at each start and a minus one at each end. I sort with ends first and keep the largest running total.
To intersect two sorted lists, I take the later start and the earlier end, and I drop the one that ends first. Sorting costs n log n.
Checkpoint · Merging
Q1/5 How does the merge join overlapping events?
Answer: B
The merge sorts by start and keeps one open block. Each event is compared with that block's end only.
Q2/5 Why can the scan ignore the older blocks?
Answer: B
After the sort, starts never go down. A block that ends before the current start ends before every later start too, so it is final.
Q3/5 Two events are [2, 5] and [5, 8], as slot numbers with both ends counted. What does the merge return?
Answer: B
The later start is 5 and the earlier end is 5. With both ends counted, a shared slot means overlap, so the events join.
Q4/5 Two meetings are [9, 10) and [10, 11) in minutes, with the end excluded. Do they overlap?
Answer: B
With the end excluded, two ranges overlap only when the later start is less than the earlier end. Ten is not less than ten.
Q5/5 The events are [1, 10], [2, 4] and [5, 7]. What does the merge return?
Answer: C
The block keeps the larger end. The event [2, 4] ends inside [1, 10], so the end stays 10, and [5, 7] also starts inside the block.
Checkpoint · Insert, sweep and intersect
Q1/5 A sorted calendar holds [1, 3], [6, 8] and [10, 12]. You insert [7, 11] with slot numbers. What is the result?
Answer: C
The new event reaches [6, 8] and [10, 12], so it grows to [6, 12]. The slot [1, 3] ends before 7 and is copied unchanged.
Q2/5 Two meetings are [0, 5) and [5, 10) in minutes. In the sweep, what must come first at minute 5?
Answer: B
If the +1 came first, the count would reach 2 and report two rooms. Ends first gives 1, which is correct.
Q3/5 Anna is free at [1, 4] and [6, 9]. Ben is free at [3, 7]. Which slots are free for both?
Answer: C
For each pair, take the later start and the earlier end: [3, 4] from the first pair and [6, 7] from the second.
Q4/5 A user wants to keep as many events as possible with no two overlapping. What do you sort by?
Answer: B
Sorting by start fails on [1, 10], [2, 3], [4, 5]: it keeps 1 event, and sorting by end keeps 2.
Q5/5 What is the cost of the merge, with the sort included?
Answer: B
The scan costs O(n) and the sort costs O(n log n). The larger term gives O(n log n).
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Meeting time overlap check | Platform | Easy | A sort, then neighbours |
| 2 | Carve a blackout out of the free slots | Rides | Easy | Keeping the parts outside one range |
| 3 | Merge the overlapping slots | Observe | Medium | Sort by start, then join with the larger end |
| 4 | Insert a new slot and merge | Ads | Medium | Three phases on a sorted calendar |
| 5 | Rooms needed for the meetings | Bank | Medium | The sweep over start and end times |
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.