Merge two sorted lists in linear time.
Use it when two lists are already sorted and you need one ordered list, or a question about both lists at once. Signal words: two sorted lists, already in order, merge, in common, overlap, both lists.
Start one pointer at the front of each list, and an empty answer.
Step compare the two fronts. Take the smaller and move only its pointer. Equal fronts: a merge takes one and keeps the other for the next step; a shared-values search keeps one and moves both pointers.
Stop when either list runs out. A merge then copies the rest of the other list; a shared-values search stops, because nothing more can match.
It does not work on lists that are not sorted. Sort them first, or use a hash set.
Cost: each step moves a pointer forward by at least one, so at most n + m steps: O(n + m) time, and O(n + m) space for the new list.
In this lesson you learn to combine two sorted lists in one pass. One pointer waits at the front of each list, and every step takes the smaller front value.
At a delivery hub, parcels pass two scanning gates, Gate A and Gate B. Each gate saves the time of every scan, in seconds since midnight, in the order the scans happened. So each list is already sorted. Your team lead sets the requirement for the tracking page.
Your team lead says: The tracking page needs one timeline of every scan from both gates, in time order, refreshed every second.
Each gate sends up to a million scans, and the page has 100 milliseconds to build the timeline.
Here is a short test. Gate A saw scans at [4, 9, 15, 22] and Gate B at [6, 9, 11, 30, 41]. The timeline reads [4, 6, 9, 9, 11, 15, 22, 30, 41]. A scan at the same second on both gates appears twice, because they are two scans.
So the task is this: merge two sorted lists into one sorted list, fast.
Picture two queues of people, each sorted by ticket number, so the lowest number stands first. One clerk must call everyone in number order.
The clerk looks at the first person in each queue and calls the lower number. That person leaves, and the next person in that queue steps forward. The other queue does not change.
When one queue is empty, the clerk calls the other queue from front to back, with no more comparing. The clerk never looks behind the first person, because a queue is sorted. The two front people are the two pointers of this lesson.
Two sorted queues at one ticket window: the clerk always calls the lower of the two front numbers.
Before you write code, build the timeline for the test scans by hand. It takes a minute, and it shows you what the work really is.
Solve it by hand: Two gates' scan times by hand: one timeline. The hand-solve sheet loads in your browser.
You work at the whiteboard. You put a finger on the first scan of each gate. You write down the smaller one, and you move only that finger.
Input: Gate A [4, 9, 15, 22], Gate B [6, 9, 11, 30, 41].
| Step | A finger | B finger | Compared | Written | Timeline so far |
|---|---|---|---|---|---|
| 1 | 4 | 6 | 4 is smaller | 4, from A | 4 |
| 2 | 9 | 6 | 6 is smaller | 6, from B | 4, 6 |
| 3 | 9 | 9 | equal: A goes first | 9, from A | 4, 6, 9 |
| 4 | 15 | 9 | 9 is smaller | 9, from B | 4, 6, 9, 9 |
| 5 | 15 | 11 | 11 is smaller | 11, from B | 4, 6, 9, 9, 11 |
| 6 | 15 | 30 | 15 is smaller | 15, from A | 4, 6, 9, 9, 11, 15 |
| 7 | 22 | 30 | 22 is smaller | 22, from A | 4, 6, 9, 9, 11, 15, 22 |
After step 7, Gate A has no scans left. You copy the rest of Gate B, 30 and 41, without comparing. The timeline has 9 scans, and each scan was written once.
Look at what you never did. You never went back, and you never compared two scans of the same gate.
Remember this. You will use it soon.
You turn the hand method into code. You want a correct version first.
Start with something correct. Put both lists into one list and sort it.
def merge_by_sorting(first, second):
joined = first + second # one list with every scan
joined.sort() # let the library put it in order
return joinedThis is correct, and it is short. A general sort of n values compares about n × log2 n pairs, so it is O(n log n). The team keeps it as the reference: every faster version must give the same timeline.
It also ignores something. Both lists were in order before the join, and the sort cannot know that. It puts the order back from scratch.
Now check real traffic.
At peak, each gate sends 1,000,000 scans, and the page refreshes every second with a budget of 100 ms.
Here is the count for one refresh:
So the first attempt takes about four times the budget. A faster computer helps a little. A better idea helps a lot.
Predict the cost
Q Each refresh joins two sorted lists of 1,000,000 scans each and sorts them with a general comparison sort. About how long does that take at 10^8 operations a second?
Answer: C
A general sort makes about n log2 n comparisons: 2,000,000 × 21 is about 42 million, or about 0.42 seconds. It does not use the fact that each list is sorted, so the budget of 0.1 seconds is missed by a wide margin.
The first attempt is correct, and it wastes the order that the gates already give. Now the team asks how to use it.
Look at your two fingers on the whiteboard.
Your fingers already did it. Each gate is sorted, so only the two fronts matter. Can we do better than sorting?
Think about the merged timeline. Its first scan must be the smallest scan of all. The smallest scan of a sorted list is its first one, so the smallest scan of all is one of the two fronts. You need only to compare the two fronts.
After you take it, the same reasoning holds for what is left. The next scan of the timeline is again one of the two new fronts. So the method is:
i marks the front of the first list, and j marks the front of the second.Every step takes exactly one value, so the merge makes n + m steps for two lists of n and m values. It never goes back, and it never compares two values of the same list. This walk is called a merge. It is the step that gives merge sort its name.
| Step | i, j before | Fronts | Smaller | What happens | i, j after | Merged after |
|---|---|---|---|---|---|---|
| 1 | 0, 0 | 4 and 6 | 4 | take 4 from A | 1, 0 | 4 |
| 2 | 1, 0 | 9 and 6 | 6 | take 6 from B | 1, 1 | 4, 6 |
| 3 | 1, 1 | 9 and 9 | tie | take 9 from A | 2, 1 | 4, 6, 9 |
| 4 | 2, 1 | 15 and 9 | 9 | take 9 from B | 2, 2 | 4, 6, 9, 9 |
| 5 | 2, 2 | 15 and 11 | 11 | take 11 from B | 2, 3 | 4, 6, 9, 9, 11 |
| 6 | 2, 3 | 15 and 30 | 15 | take 15 from A | 3, 3 | 4, 6, 9, 9, 11, 15 |
| 7 | 3, 3 | 22 and 30 | 22 | take 22 from A | 4, 3 | 4, 6, 9, 9, 11, 15, 22 |
| 8 | 4, 3 | A is empty | none | copy 30 and 41 from B | 4, 5 | 4, 6, 9, 9, 11, 15, 22, 30, 41 |
Race: Sort the joined lists, against merging them. The operation counter loads in your browser.
The race counts the work of each version on random scan times. At 10,000 scans from each gate, a textbook sort of the joined list makes 260,913 comparisons. The merge makes 20,000 moves. At a million scans from each gate, that gap is the difference between 0.42 seconds and 0.02 seconds.
One honest note. Python's own sort notices runs that are already in order, so it merges them and runs fast on this input. Many general sorts do not notice. Relying on that is fragile, and the merge is the step that other problems need, as the rest of this lesson shows.
Exercise · Predict the output: Where does the loop stop?. The loop takes the smaller front, and a tie takes from the first list. It stops as soon as one list runs out, and the tail is not copied yet. What does this print?
first = [1, 4, 4, 9]
second = [4, 6, 7]
merged = []
i = 0
j = 0
while i < len(first) and j < len(second):
if first[i] <= second[j]:
merged.append(first[i])
i += 1
else:
merged.append(second[j])
j += 1
print(i, j, *merged)Merge: compare the two fronts, take the smaller, move that pointer, and copy the rest when one list runs out.
Two gates at a second hub saved [2, 5, 5, 12] and [1, 5, 8]. The player stops at five steps and asks you to predict.
Dry run: Predict each step: a second pair of gates. The step-by-step player loads in your browser.
Reading without the player? Cover the last two columns and predict them row by row.
| Step | i, j before | Fronts | What happens | i, j after | Merged after |
|---|---|---|---|---|---|
| 1 | 0, 0 | 2 and 1 | take 1 from B | 0, 1 | 1 |
| 2 | 0, 1 | 2 and 5 | take 2 from A | 1, 1 | 1, 2 |
| 3 | 1, 1 | 5 and 5 | tie: take 5 from A | 2, 1 | 1, 2, 5 |
| 4 | 2, 1 | 5 and 5 | tie: take 5 from A | 3, 1 | 1, 2, 5, 5 |
| 5 | 3, 1 | 12 and 5 | take 5 from B | 3, 2 | 1, 2, 5, 5, 5 |
| 6 | 3, 2 | 12 and 8 | take 8 from B | 3, 3 | 1, 2, 5, 5, 5, 8 |
| 7 | 3, 3 | B is empty | copy 12 from A | 4, 3 | 1, 2, 5, 5, 5, 8, 12 |
Look at steps 3 and 4. A tie takes from the first list, and the second list's 5 waits. It is taken in step 5. All three 5s survive, because a merge keeps every value.
Here is the rule that keeps the merge correct. Every line of the templates below exists to protect it.
Every value taken so far is no larger than any value still waiting in either list, and the taken values are in order.
At the start, nothing is taken, so the rule holds. Now take one step. The two fronts are the smallest values still waiting, because each list is sorted. The smaller front is no larger than every value left in either list, so it can join the end of the taken values in order.
When one list is empty, the other holds only values at least as large as the taken ones, and it is in order. Copying it keeps the rule true, and the merge is complete.
Use it when two lists are already sorted and you need one ordered list, or a question about both lists at once. Signal words: two sorted lists, already in order, merge, in common, overlap, both lists.
Start: one pointer at the front of each list, and an empty answer.
Step: compare the two fronts. Take the smaller and move only its pointer. Equal fronts: a merge takes one and keeps the other for the next step; a shared-values search keeps one and moves both pointers.
Stop: when either list runs out. A merge then copies the rest of the other list; a shared-values search stops, because nothing more can match.
It does not work on lists that are not sorted. Sort them first, or use a hash set.
Cost: each step moves a pointer forward by at least one, so at most n + m steps: O(n + m) time, and O(n + m) space for the new list.
def merge_sorted(first, second):
# [1] One pointer at the front of each list; the merged list is empty.
merged = []
i = 0
j = 0
# [2] While both lists have values left, compare their front values.
while i < len(first) and j < len(second):
# [3] The front of first is smaller or equal: take it. On a tie, first goes first.
if first[i] <= second[j]:
merged.append(first[i])
i += 1
# [4] The front of second is smaller: take it.
else:
merged.append(second[j])
j += 1
# [5] One list has run out: everything left in the other is larger than all taken, so copy it.
while i < len(first):
merged.append(first[i])
i += 1
while j < len(second):
merged.append(second[j])
j += 1
# [6] Report the merged list, in order.
return mergedpublic int[] mergeSorted(int[] first, int[] second) {
// [1] One pointer at the front of each list; the merged list is empty.
int[] merged = new int[first.length + second.length];
int size = 0;
int i = 0;
int j = 0;
// [2] While both lists have values left, compare their front values.
while (i < first.length && j < second.length) {
// [3] The front of first is smaller or equal: take it. On a tie, first goes first.
if (first[i] <= second[j]) {
merged[size++] = first[i];
i++;
}
// [4] The front of second is smaller: take it.
else {
merged[size++] = second[j];
j++;
}
}
// [5] One list has run out: everything left in the other is larger than all taken, so copy it.
while (i < first.length) {
merged[size++] = first[i];
i++;
}
while (j < second.length) {
merged[size++] = second[j];
j++;
}
// [6] Report the merged list, in order.
return merged;
}vector<int> mergeSorted(vector<int>& first, vector<int>& second) {
// [1] One pointer at the front of each list; the merged list is empty.
vector<int> merged;
size_t i = 0;
size_t j = 0;
// [2] While both lists have values left, compare their front values.
while (i < first.size() && j < second.size()) {
// [3] The front of first is smaller or equal: take it. On a tie, first goes first.
if (first[i] <= second[j]) {
merged.push_back(first[i]);
i++;
}
// [4] The front of second is smaller: take it.
else {
merged.push_back(second[j]);
j++;
}
}
// [5] One list has run out: everything left in the other is larger than all taken, so copy it.
while (i < first.size()) {
merged.push_back(first[i]);
i++;
}
while (j < second.size()) {
merged.push_back(second[j]);
j++;
}
// [6] Report the merged list, in order.
return merged;
}function mergeSorted(first, second) {
// [1] One pointer at the front of each list; the merged list is empty.
const merged = [];
let i = 0;
let j = 0;
// [2] While both lists have values left, compare their front values.
while (i < first.length && j < second.length) {
// [3] The front of first is smaller or equal: take it. On a tie, first goes first.
if (first[i] <= second[j]) {
merged.push(first[i]);
i++;
}
// [4] The front of second is smaller: take it.
else {
merged.push(second[j]);
j++;
}
}
// [5] One list has run out: everything left in the other is larger than all taken, so copy it.
while (i < first.length) {
merged.push(first[i]);
i++;
}
while (j < second.length) {
merged.push(second[j]);
j++;
}
// [6] Report the merged list, in order.
return merged;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The tail that stops after one value. This merge of two sorted lists loses values at the end on some inputs. Which line is wrong?
def merge_sorted(first, second):
merged = []
i = 0
j = 0
while i < len(first) and j < len(second):
if first[i] <= second[j]:
merged.append(first[i])
i += 1
else:
merged.append(second[j])
j += 1
if i < len(first):
merged.append(first[i])
i += 1
while j < len(second):
merged.append(second[j])
j += 1
return mergedThe merge template line by line: two pointers, compare the fronts, take the smaller, then copy the rest.
Some questions ask about both lists at once, not for all values. The walk is the same, and the only change is what happens at each comparison.
A front that is smaller than the other front has no match in the other list, so it is skipped. Equal fronts are a match: the value is kept once, and both pointers move.
This template assumes each list is strictly increasing, so no value repeats inside one list.
def shared_values(first, second):
# [1] One pointer at the front of each list; no shared value found yet.
shared = []
i = 0
j = 0
# [2] While both lists have values left, compare their fronts. Once either list runs out, nothing more can match.
while i < len(first) and j < len(second):
# [3] The front of first is smaller: every value left in second is larger, so it has no match.
if first[i] < second[j]:
i += 1
# [4] The front of second is smaller: it has no match, for the same reason.
elif second[j] < first[i]:
j += 1
# [5] The fronts are equal: keep the value once, and advance both pointers.
else:
shared.append(first[i])
i += 1
j += 1
# [6] Shared values were found from the smallest up, so they are already in order.
return sharedpublic int[] sharedValues(int[] first, int[] second) {
// [1] One pointer at the front of each list; no shared value found yet.
int[] shared = new int[Math.min(first.length, second.length)];
int size = 0;
int i = 0;
int j = 0;
// [2] While both lists have values left, compare their fronts. Once either list runs out, nothing more can match.
while (i < first.length && j < second.length) {
// [3] The front of first is smaller: every value left in second is larger, so it has no match.
if (first[i] < second[j]) {
i++;
}
// [4] The front of second is smaller: it has no match, for the same reason.
else if (second[j] < first[i]) {
j++;
}
// [5] The fronts are equal: keep the value once, and advance both pointers.
else {
shared[size++] = first[i];
i++;
j++;
}
}
// [6] Shared values were found from the smallest up, so they are already in order.
return java.util.Arrays.copyOf(shared, size);
}vector<int> sharedValues(vector<int>& first, vector<int>& second) {
// [1] One pointer at the front of each list; no shared value found yet.
vector<int> shared;
size_t i = 0;
size_t j = 0;
// [2] While both lists have values left, compare their fronts. Once either list runs out, nothing more can match.
while (i < first.size() && j < second.size()) {
// [3] The front of first is smaller: every value left in second is larger, so it has no match.
if (first[i] < second[j]) {
i++;
}
// [4] The front of second is smaller: it has no match, for the same reason.
else if (second[j] < first[i]) {
j++;
}
// [5] The fronts are equal: keep the value once, and advance both pointers.
else {
shared.push_back(first[i]);
i++;
j++;
}
}
// [6] Shared values were found from the smallest up, so they are already in order.
return shared;
}function sharedValues(first, second) {
// [1] One pointer at the front of each list; no shared value found yet.
const shared = [];
let i = 0;
let j = 0;
// [2] While both lists have values left, compare their fronts. Once either list runs out, nothing more can match.
while (i < first.length && j < second.length) {
// [3] The front of first is smaller: every value left in second is larger, so it has no match.
if (first[i] < second[j]) {
i++;
}
// [4] The front of second is smaller: it has no match, for the same reason.
else if (second[j] < first[i]) {
j++;
}
// [5] The fronts are equal: keep the value once, and advance both pointers.
else {
shared.push(first[i]);
i++;
j++;
}
}
// [6] Shared values were found from the smallest up, so they are already in order.
return shared;
}Values in both lists: skip the smaller front, and on equal fronts keep the value once and move both pointers.
Exercise · Put it in order: Do the gates share a scan time?. Arrange the lines into a function that returns true when two sorted lists have a value in common. It walks both lists with one pointer each.
def has_shared(first, second):
i = 0
j = 0
while i < len(first) and j < len(second):
if first[i] == second[j]:
return True
if first[i] < second[j]:
i += 1
else:
j += 1
return False
if first[i] != second[j]: return FalseAn online store keeps a sorted list of product ids for each of two warehouses. The shop wants the ids that both warehouses stock, so an order can ship from one place. Warehouse A holds [3, 8, 14, 21, 30], and warehouse B holds [5, 8, 21, 22, 30, 35].
This is Template 2.
| Step | i | j | first[i] | second[j] | What happens | Shared after |
|---|---|---|---|---|---|---|
| 1 | 0 | 0 | 3 | 5 | 3 is smaller: skip it | none |
| 2 | 1 | 0 | 8 | 5 | 5 is smaller: skip it | none |
| 3 | 1 | 1 | 8 | 8 | equal: keep 8, move both | 8 |
| 4 | 2 | 2 | 14 | 21 | 14 is smaller: skip it | 8 |
| 5 | 3 | 2 | 21 | 21 | equal: keep 21, move both | 8, 21 |
| 6 | 4 | 3 | 30 | 22 | 22 is smaller: skip it | 8, 21 |
| 7 | 4 | 4 | 30 | 30 | equal: keep 30, move both | 8, 21, 30 |
Both warehouses stock the ids 8, 21 and 30. After step 7, the first list has no values left, so the walk stops. The value 35 in the second list could never match.
Real production data brings edge cases.
Gate B was offline, so its list is empty: first = [1, 2, 3], second = []. The loop never runs, and the tail copy writes all of the first list.
The same happens the other way round, and for [] and []. The answer is an empty list. No special case is needed.
Gate A scanned in the morning and Gate B in the evening: [1, 2, 3] and [10, 20]. Every step takes from A, and A runs out. The tail copy then writes 10 and 20 without any comparison.
The merge makes 3 comparisons for 5 values. That is the cheapest case, and it is still correct.
For [5] and [5], a merge returns [5, 5]. The tie takes from the first list, then the second list's 5 is the only value left, and the tail copy writes it.
If the timeline must show each scan once, that is a different rule: see the shared-values template, or the first practice problem.
Gate A may scan twice in the same second: first = [2, 6, 6, 9], second = [3, 6, 8, 100]. The merge returns [2, 3, 6, 6, 6, 8, 9, 100]. All three 6s stay, and they are in order.
Template 2 assumes no repeats inside a list. With repeats, a shared value can be matched once for each pair, so the rule for what to count must be decided first.
Exercise · Break it: Find the lists this walk lists twice. Both lists are sorted. This walk should list each shared value once, but it keeps a value on every match. Find two lists where it gives the wrong answer.
def shared_values(first, second):
shared = []
i = 0
j = 0
while i < len(first) and j < len(second):
if first[i] < second[j]:
i += 1
elif second[j] < first[i]:
j += 1
else:
shared.append(first[i])
i += 1
j += 1
return sharedThis version stops when the loop ends and returns merged:
while i < len(first) and j < len(second):
...
return merged # bug: one list may still hold valuesCounterexample: first = [1, 2], second = [3, 4]. The bug returns [1, 2]. The correct answer is [1, 2, 3, 4].
The loop ends as soon as the first list runs out. The values 3 and 4 were never taken. After the loop, one list can still hold values, so copy what is left of both lists.
When one list runs out the loop ends, but the other list still holds values: forget to copy the rest and they are lost.
This version treats equal fronts like the shared-values template: it takes one value and moves both pointers.
Counterexample: first = [5], second = [5]. The bug returns [5]. A merge must return [5, 5], because there are two scans.
Dropping one of two equal values is a rule for unions and shared values. It is not a merge. Choose the rule from the question: keep both, keep one, or keep only the shared value.
On a tie, take one value and move one pointer. Moving both pointers drops a value that should stay.
A tempting shortcut is to run the merge on a list from a gate whose clock was wrong, so its scans are not in order.
Counterexample: first = [9, 4], second = [6]. The merge returns [6, 9, 4], which is not in order.
The merge trusts that each list is sorted, and nothing checks it. When the input may be unsorted, sort each list first, or use a different method.
Your team lead brings a request from the support team. They want the parcel ids that appear in both of two lists of complaints. The lists arrive in no order, for example [9, 4, 7] and [7, 1, 9].
The shared-values walk needs both lists sorted. Sorting costs O(n log n), and that is fine for one query. But when one list is small and the other is huge, a hash set of the small list answers each value in one step.
You will build that in the hashing module. For sorted lists of similar size, the walk is the simpler and cheaper choice.
Your team lead brings four product changes. Each one keeps the idea of two fronts and one pointer per list.
A chat app keeps a message buffer with spare room at its end. A new sorted batch of messages must be merged into it, with no second buffer. For the buffer [1, 3, 8] with three free slots and the batch [2, 4, 9], the result is [1, 2, 3, 4, 8, 9].
Start both pointers at the back and write the larger value into the last free slot. The write pointer never overtakes the unread values, so no second buffer is needed (LeetCode 88: Merge Sorted Array).
A chat app builds one conversation log from a phone and a laptop. A message that reached both devices must appear once. For [2, 3, 5, 8] and [1, 3, 4, 8, 10, 11], the log is [1, 2, 3, 4, 5, 8, 10, 11].
It is the merge with one change: on equal fronts, take one value and move both pointers. It is the first practice problem (LeetCode 21: Merge Two Sorted Lists, with duplicates removed).
A parcel-delivery app plans a loading dock and a driver, each with a sorted list of free time slots. A truck can load only when both are free. For the dock slots [[0, 5], [8, 12]] and the driver slots [[3, 9]], the shared periods are [3, 5] and [8, 9].
Compare the current slot of each list, keep the overlap if it lasts at least a minute, and move past the slot that ends first. It is the third practice problem (LeetCode 986: Interval List Intersections).
A monitoring system collects sorted logs from 50 services and needs one timeline. Merging two lists at a time, in order, costs too much, because the first list is copied over and over.
Keep the front of every list in a min-heap. Take the smallest front, and push the next value of that list. That is O(N log k) for N values in k lists (LeetCode 23: Merge k Sorted Lists).
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate why a merge compares only the two front values. Then explain why it can copy the rest of a list when the other runs out. 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 built it.
Each list is sorted, so the smallest value left is always one of the two fronts.
I take the smaller front and move only its pointer. When a list runs out, I copy the rest of the other one.
Every step takes one value, so it is n plus m steps. Sorting everything again would cost much more.
Both lists are already sorted, so I would merge them with two pointers, instead of joining them and sorting. Sorting costs O(n log n) and ignores the order we already have.
I keep one pointer at the front of each list. I compare the two front values, take the smaller one into the answer, and move only that pointer. On a tie, a plain merge takes from the first list and keeps the other value for the next step.
When one list runs out, everything left in the other is larger than what I have taken, so I copy it without comparing.
Each step takes one value, so it is n plus m steps: O(n + m) time, and O(n + m) space for the answer. For shared values, I keep one on a tie and move both pointers. I would test an empty list, a list entirely before the other, and equal values.
Checkpoint · Three pointers
Q1/3 Which request is a job for a three-way partition?
Answer: B
Three groups, in place, in one pass: those are the signals. Combining two sorted lists is a merge, the pair is opposite ends, and the run of stops is a sliding window.
Q2/3 In a Dutch national flag pass the value at mid is a 2. What happens next?
Answer: B
The value that came back from high has not been checked, so mid must look at it next.
Q3/3 In the middle of a pass over 9 values, low = 2, mid = 4 and high = 6. Which indexes hold 1s?
Answer: B
The 1s sit from low to mid − 1, which is indexes 2 and 3. Indexes 0 and 1 hold 0s, and indexes 4 to 6 are still unknown.
Checkpoint · Merging
Q1/7 Two sorted lists of 1,000,000 values each are joined and sorted with a general comparison sort. Why is this the slower first attempt?
Answer: B
The sort is correct, but it makes about 42 million comparisons. A merge uses the order of each list and makes about 2 million steps.
Q2/7 The merged list is [4, 6, 9] so far. The fronts are 15 in the first list and 11 in the second. What does the merge take next?
Answer: B
Each list is sorted, so the smallest value left is one of the two fronts. Take the smaller one, and move only its pointer.
Q3/7 The first list has run out. The second list still holds 30 and 41. What should the merge do?
Answer: C
Every value left in the second list is at least as large as everything taken, and the list is in order. So the rest is copied as it is.
Q4/7 Template 1 merges [5] and [5]. What does it return?
Answer: B
A merge keeps every value. The tie takes the 5 from the first list, and the 5 from the second list is copied afterwards.
Q5/7 A search service wants only the ids that appear in both of two sorted lists. What changes compared with a merge?
Answer: B
The walk is the same. The smaller front has no match in the other list, so it is skipped, and equal fronts are a match.
Q6/7 A merge of n values and m values makes at most how many steps?
Answer: C
Every step takes one value, and no pointer goes back. So there are at most n + m steps.
Q7/7 The merge runs on [9, 4] and [6]. It returns [6, 9, 4]. What is the cause?
Answer: C
The merge trusts that each list is in order. Sort the lists first, or use a different method, when that is not guaranteed.
Ten questions on this lesson and the last one. Pass with 80% or more to open the next part of the Academy map.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Merge two devices' message logs | Chat | Easy | Template 1, with one change: an equal message is kept once |
| 2 | Documents in both posting lists | Search | Easy | Template 2: the ids that two sorted lists share |
| 3 | When the dock and the driver are both free | Freight | Medium | The walk on sorted time slots, moving past the slot that ends first |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
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.