QuestionsDSA

Merge k Sorted Lists

Heap / Top-KHardDSA

Merge k sorted linked lists into one sorted list. e.g. [[1,4,5],[1,3,4],[2,6]] → 1,1,2,3,4,4,5,6.

What it tests

Using a min-heap to always know the smallest current head across k sources — the k-way merge.

Approach & answer

The naive 'concatenate then sort' is O(N log N) over all N nodes and ignores the sortedness. The heap answer: push the head of each of the k lists into a min-heap keyed by node value. Repeatedly pop the smallest, append it to the output, and push that node's `next` if it exists. The heap never holds more than k nodes, so each of the N pops/pushes costs O(log k) → O(N log k) total, strictly better than O(N log N) when k is small relative to N. This is the general k-way merge and the top-K family: 'pick the current best across many ordered sources' → a heap. An alternative with the same complexity is divide-and-conquer pairwise merging (merge lists two at a time, log k rounds), which needs no heap and is often what interviewers accept in JS where there's no built-in priority queue — you'd hand-roll a binary heap or the pairwise merge.

Use this technique when

Combine k already-sorted sources, or repeatedly need the current min/max across many streams → min-heap of the k heads.

Complexity

Time O(N log k) · Space O(k)

References

js