Merge K sorted lists

Merge several already-sorted lists into one sorted result by always taking the smallest available head, using a min-heap of the current heads.

Time O(n log k)Space O(k)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Instead of comparing all k list-heads pairwise every round, push the current head of every list onto a min-heap, keyed by value. The heap top is always the smallest head overall, so popping it is an O(log k) decision. After taking it, push the next element from whichever list it came from. The heap never holds more than k elements.

Code

public static List<int> MergeKLists(List<List<int>> lists) {
    var heap = new PriorityQueue<(int list, int idx), int>(); // min-heap by value
    for (int l = 0; l < lists.Count; l++)
        if (lists[l].Count > 0) heap.Enqueue((l, 0), lists[l][0]);
    var result = new List<int>();
    while (heap.Count > 0) {
        var (l, idx) = heap.Dequeue();
        result.Add(lists[l][idx]);
        if (idx + 1 < lists[l].Count) heap.Enqueue((l, idx + 1), lists[l][idx + 1]);
    }
    return result;
}
static List<Integer> mergeKLists(List<List<Integer>> lists) {
    PriorityQueue<int[]> heap = new PriorityQueue<>((x, y) -> x[0] - y[0]); // min-heap of {value, list, idx}
    for (int l = 0; l < lists.size(); l++)
        if (!lists.get(l).isEmpty()) heap.offer(new int[]{lists.get(l).get(0), l, 0});
    List<Integer> result = new ArrayList<>();
    while (!heap.isEmpty()) {
        int[] top = heap.poll(); int l = top[1], idx = top[2];
        result.add(lists.get(l).get(idx));
        if (idx + 1 < lists.get(l).size()) heap.offer(new int[]{lists.get(l).get(idx + 1), l, idx + 1});
    }
    return result;
}
vector<int> mergeKLists(const vector<vector<int>>& lists) {
    priority_queue<array<int, 3>, vector<array<int, 3>>, greater<>> heap; // min-heap of {value, list, idx}
    for (int l = 0; l < (int)lists.size(); l++)
        if (!lists[l].empty()) heap.push({lists[l][0], l, 0});
    vector<int> result;
    while (!heap.empty()) {
        auto [val, l, idx] = heap.top(); heap.pop();
        result.push_back(lists[l][idx]);
        if (idx + 1 < (int)lists[l].size()) heap.push({lists[l][idx + 1], l, idx + 1});
    }
    return result;
}
import heapq

def merge_k_lists(lists: list[list[int]]) -> list[int]:
    heap = []  # min-heap of (value, list, idx)
    for l in range(len(lists)):
        if lists[l]: heapq.heappush(heap, (lists[l][0], l, 0))
    result = []
    while heap:
        _, l, idx = heapq.heappop(heap)
        result.append(lists[l][idx])
        if idx + 1 < len(lists[l]): heapq.heappush(heap, (lists[l][idx + 1], l, idx + 1))
    return result

Tips

In the .NET library

This is exactly how external merge sort combines sorted runs from disk, and how a log-aggregation system merges many time-ordered streams into one.