Merge Sorted Lists
Write merge_sorted(a, b) that takes two lists, each already sorted from smallest to largest, and returns one sorted list with all the items of both. Duplicates are kept.
Understand the problem
Do a merge by hand.
Merging [1, 4, 9] and [2, 3, 10]: which number comes first, 1 or 2? Compare the front of each list. Which is the smaller front number?
Because both lists are sorted, the smallest number overall must be at the front of one of them. Compare the two fronts, take the smaller, and move on in that list.
One list runs out while the other still has items. What do you do?
- Stop: the merge is finished
- Add all the remaining items of the other list, they are already sorted
- Sort the remaining items
The remaining items are already in order, and all of them are at least as large as everything taken so far. Append them as they are. Forgetting this tail is the classic bug.
Write the solution
Return the merged list. Do not just sort a + b: practise the two-pointer walk.
def merge_sorted(a, b):
# Write your code here.
pass
Hint 1: a question to ask yourself
What is the smallest item that has not yet been taken, and where can it be?
Hint 2: the shape of the answer
Keep two positions i and j. While both lists have items left, take the smaller front item. Afterwards add whatever is left of a and of b (a[i:] and b[j:]).
Reflect
Solution
def merge_sorted(a, b):
result = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
result.extend(a[i:])
result.extend(b[j:])
return result
Another way: the standard library
import heapq
def merge_sorted(a, b):
return list(heapq.merge(a, b))
What this tests: two indexes walking along two lists, the loop condition, the leftover tail, and knowing heapq.merge.
Why not sorted(a + b)? It is correct and in Python fast (Timsort notices the two sorted runs). But the task is the walk: it uses the fact that the lists are sorted, runs in O(n + m), and is the core of merge sort and of merging many sorted files. In an interview, write the walk, then mention heapq.merge.
<= keeps the merge stable: on a tie it takes from a first.
Cost: O(n + m) time and space.
What an interviewer might ask next: Merge k sorted lists. (Use a heap of the front items: heapq.merge(*lists), O(N log k).)
VISIBLE = 3
CASES = [
(([1, 3, 5], [2, 4, 6]), [1, 2, 3, 4, 5, 6], 'interleaved'),
(([], [1]), [1], 'the first list is empty'),
(([1, 2], []), [1, 2], 'the second list is empty'),
(([1, 1], [1]), [1, 1, 1], 'duplicates are kept'),
(([1, 2, 3], [4, 5, 6]), [1, 2, 3, 4, 5, 6], 'the first list ends first'),
(([4, 5, 6], [1, 2, 3]), [1, 2, 3, 4, 5, 6], 'the second list ends first'),
(([-3, 0], [-1, 2]), [-3, -1, 0, 2], 'negative numbers'),
(([], []), [], 'both empty'),
(([1, 5, 9], [2]), [1, 2, 5, 9], 'one short list'),
]