Merge k Sorted Lists

Hard

Topics
Linked ListHeapDivide and ConquerMerge Sort

You are given an array of k sorted linked lists. Merge them into one sorted list and return its head.

Example 1

list 1145null
list 2134null
list 326null
merged11234456null
Each of the 3 input lists is already sorted, and the result must be one sorted list holding all of their nodes. The lists may differ wildly in length, and an empty one is allowed.
Linked list values from head to tail.
Input:  lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]

Example 2

no lists
Input:  lists = []
Output: []

Constraints

  • 0 <= k <= 10^4
  • 0 <= list length <= 500
  • Each list is sorted non-decreasing.
Editorial — intuition, approach, complexity and pitfalls

Intuition

The frontier of the merged list is always the smallest current head across the k lists. A min-heap of the k heads gives that smallest element in O(log k); alternatively pair up lists and merge two at a time (divide and conquer).

Approach

  1. Push the head of every non-empty list into a min-heap keyed by value.
  2. Pop the smallest, append it to the result, and push its next node.
  3. Repeat until the heap empties.

Dry Run

lists = [1,4,5], [1,3,4], [2,6]
heap entries are (value, list index, node). Shown as (value, list index).

seed              heap=[(1,0) (1,1) (2,2)]        one head per list
pop (1,0) -> 1    push (4,0)   heap=[(1,1) (2,2) (4,0)]
pop (1,1) -> 1    push (3,1)   heap=[(2,2) (4,0) (3,1)]
pop (2,2) -> 2    push (6,2)   heap=[(3,1) (4,0) (6,2)]
pop (3,1) -> 3    push (4,1)   heap=[(4,0) (6,2) (4,1)]
pop (4,0) -> 4    push (5,0)   heap=[(4,1) (6,2) (5,0)]
pop (4,1) -> 4    list spent   heap=[(5,0) (6,2)]
pop (5,0) -> 5    list spent   heap=[(6,2)]
pop (6,2) -> 6                 heap=[]

answer 1 1 2 3 4 4 5 6

Two things the trace makes visible. The heap never holds more than 3 entries --
one per list, never one per node -- which is why space is O(k) and not O(n).
And look at the two (1, ...) entries: the list index is a TIEBREAKER, not
decoration. Without it Python would fall through to comparing the third tuple
element, and ListNode has no ordering, so equal values would raise TypeError.

Complexity

  • Time — O(N log k): each of the N total nodes is pushed/popped once from a heap of size k.
  • Space — O(k): the heap holds at most one node per list.

Common Pitfalls

  • Include a tiebreaker (list index) in the heap key so nodes with equal values never get compared directly.

Full Solution — all languages

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
class Solution:
    def mergeKLists(self, lists):
        import heapq
        heap=[]
        for i,node in enumerate(lists):
            if node: heapq.heappush(heap,(node.val,i,node))
        dummy=ListNode(); tail=dummy
        while heap:
            val,i,node=heapq.heappop(heap)
            tail.next=node; tail=node
            if node.next: heapq.heappush(heap,(node.next.val,i,node.next))
        return dummy.next
SensAI
Beta
Tap the mic to stop voice mode