CodingNodes / Linked List / Merge K Sorted Lists System design Space play · ←→ step · R restart

Problem

You get an array lists of linked-list heads. Every list is already sorted from smallest to largest, and some of them can be empty.

Join all of the lists into one sorted list by re-linking the existing nodes, and return its head. If there is nothing to merge, return an empty list.

Constraints

  • 0 ≤ number of lists ≤ 10000
  • 0 ≤ length of each list ≤ 500
  • -10000 ≤ Node.val ≤ 10000
  • Each list is sorted in non-decreasing order

Examples: pick one to animate

Solutions

TimeO(N log k) SpaceO(k)

Time: Every one of the N nodes is pushed into the heap once and popped once, and each heap operation costs about log k.

Space: The heap never holds more than one node per list, so it has at most k entries. The nodes themselves are re-linked, not copied.

The next node of the answer is always the smallest front node among all k lists. Keep those front nodes in a min-heap. Pop the smallest, link it to the end of the result, and push the node that came after it in its own list. Repeat until the heap is empty.