K-way Merge

Merge k sorted lists or search across sorted rows with a min-heap of the current heads — kth smallest in a matrix, smallest range.

Intermediate 2 min readLesson 19 of 25

You have k sorted sequences and need them in one sorted order, or need the kth smallest item across them. Keep a min-heap holding the current head of each sequence. Pop the smallest head, output it, and push the next element from the same sequence.

pop min1 → 4 → 72 → 5 → 83 → 6 → 9min-heap of heads{1, 2, 3}1, 2, 3, 4 …
When to use this pattern
  • Merge k sorted lists, arrays or files (external sorting).
  • Kth smallest across several sorted lists, or in a row- and column-sorted matrix.
  • Smallest range covering at least one element from each list.
  • Pairs from two sorted arrays with the smallest sums.

Merge k sorted lists

ListNode mergeKLists(ListNode[] lists) {
    PriorityQueue<ListNode> heap = new PriorityQueue<>((a, b) -> a.val - b.val);
    for (ListNode l : lists) if (l != null) heap.offer(l);
    ListNode dummy = new ListNode(0), tail = dummy;
    while (!heap.isEmpty()) {
        ListNode n = heap.poll();
        tail = tail.next = n;
        if (n.next != null) heap.offer(n.next);     // advance that list
    }
    return dummy.next;
}
TimeO(N log k), N = total elementsSpaceO(k)Divide and conquer (merge lists in pairs) has the same complexity with no heap.

Kth smallest in a sorted matrix

Each row is a sorted list. Push the first element of every row (or of the first k rows), then pop k − 1 times, pushing the next element in the same row each time. The next top is the answer. O(k log min(k, n)).

The binary search on value alternative is often better: guess mid and count the elements ≤ mid in O(n) by walking from the bottom-left corner. O(n log(max − min)).

Smallest range covering k lists

Keep one element from each list in a min-heap and track the current maximum. The range is [heap top, max]. Pop the min and push its successor (which may raise the max). Record the best range. Stop when any list runs out.

int[] smallestRange(List<List<Integer>> nums) {
    PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[0] - b[0]); // {val, list, idx}
    int max = Integer.MIN_VALUE;
    for (int i = 0; i < nums.size(); i++) {
        heap.offer(new int[]{nums.get(i).get(0), i, 0});
        max = Math.max(max, nums.get(i).get(0));
    }
    int[] best = {heap.peek()[0], max};
    while (true) {
        int[] t = heap.poll();
        if (max - t[0] < best[1] - best[0]) best = new int[]{t[0], max};
        if (t[2] + 1 == nums.get(t[1]).size()) return best;   // one list exhausted
        int nx = nums.get(t[1]).get(t[2] + 1);
        max = Math.max(max, nx);
        heap.offer(new int[]{nx, t[1], t[2] + 1});
    }
}
Practice problems
  • Merge k Sorted Listshard
  • Kth Smallest Element in a Sorted Matrixmedium
  • Find K Pairs with Smallest Sumsmedium
  • Smallest Range Covering Elements from K Listshard
  • Merge Sorted Arrayk = 2, fill from the backeasy
  • Ugly Number IImerge three generated sequencesmedium
Key takeaways
  • Heap of the k current heads; pop the min, push its successor.
  • O(N log k) time, O(k) space.
  • Track the max alongside the heap for range problems.
  • Kth smallest can also be found by binary searching on the value.