Lesson 1 · Unit 03
Merge two sorted lists
Two pointers, one pass, and do not forget the leftovers
What you practise
- Two pointers, the leftover tail, O(n + m)
Try a question from this lesson
Pick one
Two piles of exam papers are each sorted by score, lowest on top. You want one sorted pile. Where is the lowest paper of all?
Correct answer
On top of one of the two piles
Why
Each pile has its own lowest paper on top, so the overall lowest is one of those two. Take it, and the same is true again for what remains. No searching: that is the whole idea of merging.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Merge
Keep one pointer per list: i in a, j in b. Compare the two items they point at, copy the smaller one to the output, and advance that pointer.
The loop ends when either list runs out. Whatever is left in the other list is already sorted and larger than everything copied so far, so it is appended as it is.
def merge(a, b):
out = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i])
i += 1
else:
out.append(b[j])
j += 1
return out + a[i:] + b[j:]function merge(a, b) {
const out = [];
let i = 0, j = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) {
out.push(a[i]);
i++;
} else {
out.push(b[j]);
j++;
}
}
out.push(...a.slice(i), ...b.slice(j));
return out;
}function merge(a: number[], b: number[]) {
const out: number[] = [];
let i = 0, j = 0;
while (i < a.length && j < b.length) {
if (a[i] <= b[j]) {
out.push(a[i]);
i++;
} else {
out.push(b[j]);
j++;
}
}
out.push(...a.slice(i), ...b.slice(j));
return out;
}Python noteA slice that starts past the end, like a[i:] when i == len(a), is just an empty list. So one of the two tails adds nothing.
JavaScript noteout.push(...a.slice(i)) spreads the leftover items into separate arguments, so each one is pushed.
TypeScript noteconst out: number[] = [] needs its annotation: an empty array literal gives TypeScript nothing to infer the item type from.
10 more exercises in the app
- 2× type the answer
- 4× multiple choice
- 1× fill the blanks
- 2× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.