Merge k Sorted Lists

HardK-Way Merge · Heap / Divide & Conquer🧩 K-Way MergeLeetCode #23 ↗Updated

Problem

You get an array of k singly linked lists, each already sorted in ascending order (some may be empty, and the array itself may be empty). Combine them into one ascending linked list and return its head.
Input[[1,4,5],[1,3,4],[2,6]]Output[1,1,2,3,4,4,5,6]
Input[]Output[]
Input[[]]Output[]

0 ≤ k ≤ 104  ·  0 ≤ list length ≤ 500  ·  -104 ≤ val ≤ 104  ·  total nodes N ≤ 104

Try it yourself

Java
class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
At every step the next output node is the smallest of the k current heads. Find it with a heap in O(log k), or merge lists pairwise in rounds so each node is touched only log k times.
PatternK-Way Merge

Instinct Several sorted lists, rows or streams and you need the global order, the k-th smallest or a range: keep one cursor per list in a min-heap.

Memory hack Line up the heads, crown the smallest, then let its next-in-line step up.

Open the K-Way Merge guide →

Approaches

Brute ForceCollect All Values & Sort

Time O(N log N)Space O(N)

Throw away the sortedness: dump every value into a list, sort it, and build a fresh linked list from the sorted values.

Java
public ListNode mergeKLists(ListNode[] lists) {
    List<Integer> values = new ArrayList<>();
    for (ListNode node : lists) {
        for (; node != null; node = node.next) values.add(node.val);
    }
    Collections.sort(values);
    ListNode dummy = new ListNode(0), tail = dummy;
    for (int v : values) {
        tail.next = new ListNode(v);
        tail = tail.next;
    }
    return dummy.next;
}

Simple, but ignores that inputs are sorted and allocates N new nodes.

At a glance

LevelApproachTimeSpace
Brute ForceCollect All Values & SortO(N log N)O(N)
BetterMin-Heap of List HeadsO(N log k)O(k)
OptimalDivide & Conquer Pairwise MergeO(N log k)O(log k)
Common pitfalls
  • Pushing null heads into the heap — NPE in the comparator.
  • Merging sequentially (result = merge(result, listi)) — O(N·k), not O(N log k).
  • Forgetting the empty-array case k = 0 in divide & conquer.
Interview tips
  • State N (total nodes) vs k (lists) clearly before giving complexities.
  • Offer both O(N log k) solutions and compare: heap = O(k) space, D&C = O(log k).
  • Reuse Merge Two Sorted Lists (21) as a helper — say so explicitly.
Pattern
K-way merge (min-heap of heads) → combine k sorted sequences or find the k-th smallest across them.
My notes saved in this browser