Quant Memo
Coding/●●●●

Merge k sorted streams lazily

Asked at Two Sigma, HRT

You are handed k sorted input streams (think: per-exchange tick files, each ordered by timestamp). Produce a single iterator that yields every element in global sorted order.

The streams may be enormous or even unbounded, so you may not read them fully into memory, hold at most one pending element per stream.

[1, 4, 7], [2, 5], [3, 6]   ->  1, 2, 3, 4, 5, 6, 7

Target O(Nlogk)O(N \log k) total time for NN elements, and O(k)O(k) memory.

Show a hint

The smallest unseen element is always the smallest among the current fronts of the k streams. A min-heap of those fronts gives you that in O(logk)O(\log k), and when you pop a stream's front, pull its next element to replace it.

Your answer

This one is open-ended. Work it through, then check your reasoning against the full solution.

More Coding questions