Skip to content
mlmentorship

Merge K Sorted Lists

Merge many sorted linked lists into one sorted list.

Published · 10 min read ·Specialist ·Advanced

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Merge K Sorted Lists

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A finite list of linked-list head references, each describing a nondecreasing integer chain or an empty chain. Output. Return the head of one nondecreasing chain containing every node from every input list. Rules. Reuse the original nodes and rewrite their links rather than copying values into replacement nodes. Input chains must be acyclic and pairwise node-disjoint. Equal values remain separate occurrences. Leave the head array unchanged. Empty sources contribute nothing; no nodes returns None. Example. Chains 1 -> 4, 1 -> 3, and 2 -> 6 merge into 1 -> 1 -> 2 -> 3 -> 4 -> 6. Both nodes valued 1 must remain in the result.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

A min-heap containing one current head per nonempty list always exposes the globally smallest unmerged node.

Problem trace

Emitting one frontier advances only the list that supplied it

Worked example: advance the list that supplied the minimum, then compare againCurrent heads are (1,4,2). After emitting 1 and exposing 9, the next minimum is 2, not the next value from that same list.Advance one source head, then compareall exposed heads againInitial heads: one is the minimum1942One was emitted; its source nowexposes nine942Next minimum is 2, not nine.
Read it this way: Current heads are (1,4,2). After emitting 1 and exposing 9, the next minimum is 2, not the next value from that same list. After emitting one, why is its successor nine not automatically the next output?
Full interview answer 10 min read
Reading depth

Combine several sorted linked lists into one sorted chain containing their original nodes exactly once.

Problem

Input. A finite list of linked-list head references, each describing a nondecreasing integer chain or an empty chain.

Output. Return the head of one nondecreasing chain containing every node from every input list.

Rules. Reuse the original nodes and rewrite their links rather than copying values into replacement nodes. Input chains must be acyclic and pairwise node-disjoint. Equal values remain separate occurrences. Leave the head array unchanged. Empty sources contribute nothing; no nodes returns None.

Example. Chains 1 -> 4, 1 -> 3, and 2 -> 6 merge into 1 -> 1 -> 2 -> 3 -> 4 -> 6. Both nodes valued 1 must remain in the result.

Picture

For A:1->4, B:1->3, keep candidates (1,0,A) and (1,1,B). Emit A’s 1, then replace only A’s candidate with 4. B’s 1 is now smallest.

Problem trace

Emitting one frontier advances only the list that supplied it

Input and goalMerge many sorted linked lists into one sorted list.
Seed one head from each listPush tuples (1,0,A1), (1,1,B1), and (2,2,C2). The list index breaks the value-1 tie, so A1 is the root.
inputListsA:1->4->5; B:1->3->4; C:2->6heapArray[(1,0,A1),(1,1,B1),(2,2,C2)]taildummyoutputOrder[]
input lists
A:1->4->5; B:1->3->4; C:2->6
heap array
[(1,0,A1),(1,1,B1),(2,2,C2)]
tail
dummy

Recognize it
Use it when k individually sorted streams must be merged and only their current heads can be candidates for the next global minimum.
Keep true
The heap contains exactly the first unmerged node of each nonexhausted list, and the tail follows all nodes already popped in nondecreasing tuple order.
Reuse it
For sorted sources, keep only one frontier item per source and replace it from the same source after extraction. The pattern transfers to external merge, log aggregation, and k-way iterators.
Push tuples (1,0,A1), (1,1,B1), and (2,2,C2). The list index breaks the value-1 tie, so A1 is the root. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does emitting A1 add A4 to the heap but leave the B and C frontiers unchanged?
Reference drawing

Problem trace

Emitting one frontier advances only the list that supplied it

Worked example: advance the list that supplied the minimum, then compare againCurrent heads are (1,4,2). After emitting 1 and exposing 9, the next minimum is 2, not the next value from that same list.Advance one source head, then compareall exposed heads againInitial heads: one is the minimum1942One was emitted; its source nowexposes nine942Next minimum is 2, not nine.
Execution trace
Input and goalMerge many sorted linked lists into one sorted list.
Seed one head from each listPush tuples (1,0,A1), (1,1,B1), and (2,2,C2). The list index breaks the value-1 tie, so A1 is the root.
inputListsA:1->4->5; B:1->3->4; C:2->6heapArray[(1,0,A1),(1,1,B1),(2,2,C2)]taildummyoutputOrder[]
input lists
A:1->4->5; B:1->3->4; C:2->6
heap array
[(1,0,A1),(1,1,B1),(2,2,C2)]
tail
dummy

Recognize it
Use it when k individually sorted streams must be merged and only their current heads can be candidates for the next global minimum.
Keep true
The heap contains exactly the first unmerged node of each nonexhausted list, and the tail follows all nodes already popped in nondecreasing tuple order.
Reuse it
For sorted sources, keep only one frontier item per source and replace it from the same source after extraction. The pattern transfers to external merge, log aggregation, and k-way iterators.
Push tuples (1,0,A1), (1,1,B1), and (2,2,C2). The list index breaks the value-1 tie, so A1 is the root. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does emitting A1 add A4 to the heap but leave the B and C frontiers unchanged?
Read it this way: Current heads are (1,4,2). After emitting 1 and exposing 9, the next minimum is 2, not the next value from that same list. After emitting one, why is its successor nine not automatically the next output?

Every hidden source node is at least its exposed head. The heap minimum is therefore globally safe. The source index resolves equal values without comparing node objects.

Code

This local definition supplies the platform node type before the unchanged reference.

class ListNode:
   def __init__(self, val: int = 0, next_node: "ListNode | None" = None):
      self.val = val
      self.next = next_node
import heapq

def merge_k_lists(lists: list[ListNode | None]) -> ListNode | None:
   heap: list[tuple[int, int, ListNode]] = []
   for index, node in enumerate(lists):
      if node:
         heapq.heappush(heap, (node.val, index, node))

   dummy = ListNode(0)
   tail = dummy
   while heap:
      _, index, node = heapq.heappop(heap)
      tail.next = node
      tail = node
      if node.next:
         heapq.heappush(heap, (node.next.val, index, node.next))
   return dummy.next

Cost: scalar operations and heap space for k sources and n nodes. The reference allocates only one dummy node.

The platform supplies ListNode with val and next; this snippet assumes that definition.

Change the Requirement

New task: Return independent output nodes.

Picture and change: Copy the emitted value instead of reusing its node.

Code: Use heapq and ListNode above.

def merge_k_lists_copy(lists: list[ListNode | None]) -> ListNode | None:
   heap = [(node.val, index, node) for index, node in enumerate(lists) if node]
   heapq.heapify(heap)
   dummy = tail = ListNode()
   while heap:
      value, index, node = heapq.heappop(heap)
      tail.next = ListNode(value)
      tail = tail.next
      if node.next:
         heapq.heappush(heap, (node.next.val, index, node.next))
   return dummy.next

Check: A:1->4, B:1->3 yield fresh 1->1->3->4 nodes; both inputs retain their links.

Use when: Output ownership must be independent; allocation adds .

Consume Sorted Iterables

New task: Merge values without linked nodes.

Picture and change: Each heap entry owns one iterator and its current value.

Code: The collection of sources must be finite.

def merge_sorted_iterables(sources):
   heap = []
   for index, source in enumerate(sources):
      iterator = iter(source)
      try:
         value = next(iterator)
      except StopIteration:
         continue
      heapq.heappush(heap, (value, index, iterator))
   while heap:
      value, index, iterator = heapq.heappop(heap)
      yield value
      try:
         following = next(iterator)
      except StopIteration:
         continue
      heapq.heappush(heap, (following, index, iterator))

Check: list(merge_sorted_iterables([[1,4],[1,3],[]])) returns [1,1,3,4].

Use when: Sources advance lazily; heap state remains .

Reconstruct

Why require disjoint nodes for the relinking reference?

Reasoned answer

If two heads reference the same node, that object can enter the heap twice. Appending it twice may set its next pointer to itself, creating a cycle. Equal values are safe; repeated identities are not. The copy variant avoids output-link mutation but still assumes finite acyclic source traversals.

Infinite value streams need a separate liveness contract. An infinite sequence of equal values from one source can indefinitely postpone equal values from another source. Sorted output does not imply fairness among sources.