Skip to main content
Hard Heap / Priority Queue High frequency

Merge K Sorted Lists

Open on LeetCode

Approach Summary

Use a min-heap of size k storing (value, list_index, node). Extract min, add to result, push next node from that list.

Full Solution & Approach

Merging k sorted lists naively — scan all k heads to find the minimum each time — is O(nk). A min-heap fixes the selection: push the head of every list, then repeatedly extract the minimum node, append it to the result, and push that node's next. The heap always holds at most one node per list, so each extraction is O(log k) and the total is O(n log k), where n is the total number of nodes. A dummy head keeps the result construction uniform. The heap entry must be ordered by value; because the problem guarantees distinct values in the standard version, storing nodes directly works. This is the canonical "merge k sorted streams" pattern — the same heap-of-k-heads idea merges k sorted arrays and powers external sort. Divide-and-conquer pairwise merging is the O(n log k) alternative with O(1) extra heap space.

n total nodes, each pushed and popped once with O(log k) heap work — O(n log k) time. The heap holds at most k heads — O(k) space, plus the output list.

Solution Code

Solution

import heapq

def merge_k_lists(lists):
    heap = []
    for i, head in enumerate(lists):
        if head:
            heapq.heappush(heap, (head.val, i, head))
    dummy = cur = ListNode(0)
    while heap:
        _, i, node = heapq.heappop(heap)
        cur.next = node
        cur = cur.next
        if node.next:
            heapq.heappush(heap, (node.next.val, i, node.next))
    return dummy.next

Edge Cases to Watch

  • All lists empty — return null
  • One non-empty list — merge is trivial
  • Lists of very different lengths — the heap handles them uniformly
  • Duplicate values across lists — fine for a linked-list merge

How to Recognize This Pattern

  • Merge k sorted sequences
  • Heap of k heads

Complexity Analysis

Time Complexity

O(n log k)

Space Complexity

O(k)

Tags

Linked List Heap Divide and Conquer

This site is free. If these guides are helping your prep, consider buying me a coffee. ☕

Support →
Buy me a coffee