PythiloLesson 12 of 12 · progress kept in this browser

Merge sorted feeds with bounded lookahead

A global sort requires every record to be materialized. If each input stream is already sorted, a heap can emit the next smallest record with one lookahead per stream. The memory bound depends on the number of streams instead of the total record count.

Production stream contracts must define ordering and tie behavior. This exercise works with comparable numbers and preserves duplicates. A one-pass test rejects implementations that rewind an input. A prefix test uses an infinite sorted stream, making eager consumption a correctness failure rather than merely a performance concern.

import heapq,itertools
left=iter([1,4,7])
right=iter([2,2,9])
merged=heapq.merge(left,right)
print(list(itertools.islice(merged,4)))
Your task

Implement merge_prefix(streams,n), returning at most n sorted values from already sorted iterables. Do not materialize entire streams. Reject negative n.

All lessons