Exercise: Merge sorted streams

Merging sorted inputs is the heart of merge sort, of database joins, and of "merge k sorted lists", a very common interview question.

Exercise: write merge, a generator that takes two sorted iterables and yields all their items in sorted order.

list(merge([1, 4, 9], [2, 3, 10]))  # [1, 2, 3, 4, 9, 10]
  • Work lazily, one item at a time. Don't build lists, don't call sorted. The inputs may be endless streams.
  • Keep the current front item of each input. Yield the smaller one and pull the next item from that input.
  • next(it, None) doesn't work as an "end" marker if None could be an item. A private DONE = object() sentinel is safer.
  • When one input runs out, yield from the rest of the other.

Each item is handled once, so this is O(n). For more than two inputs, heapq.merge does the same with a heap.

Press Check to run the tests.