Algo-Sim › Heaps & Priority Queues

Merge K Sorted Lists

Hard · Heaps & Priority Queues · step through it in Java, Python and C++ on your own input

Merge k sorted linked lists into one sorted list, using a min-heap that holds one candidate per list.

Problem

You are given k linked lists, each sorted in ascending order. Merge them into one sorted linked list and return its head.

Constraints

Edge cases to test

Follow-up questions

What is the divide-and-conquer alternative?
Merge lists in pairs, halving the count each round: O(N log k) time and O(1) extra space.
What if the lists are too large for memory?
External k-way merge: keep one buffered block per list in memory and the heap of heads: O(N log k) with sequential disk reads.

Solution

Java

public ListNode mergeKLists(ListNode[] lists) {
    PriorityQueue<ListNode> heap = new PriorityQueue<>((a, b) -> Integer.compare(a.val, b.val));
    for (ListNode head : lists) {
        if (head != null) heap.offer(head);
    }
    ListNode dummy = new ListNode(0), tail = dummy;
    while (!heap.isEmpty()) {
        ListNode node = heap.poll();
        tail.next = node;
        tail = node;
        if (node.next != null) heap.offer(node.next);
    }
    return dummy.next;
}

Python

import heapq


def merge_k_lists(lists):
    # Entries are (value, list index, node): the index breaks ties,
    # so two nodes are never compared directly.
    heap = []
    for i, head in enumerate(lists):
        if head:
            heapq.heappush(heap, (head.val, i, head))
    dummy = tail = ListNode(0)
    while heap:
        _, 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

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        auto cmp = [](ListNode *a, ListNode *b) { return a->val > b->val; };
        priority_queue<ListNode *, vector<ListNode *>, decltype(cmp)> heap(cmp);
        for (ListNode *head : lists) {
            if (head != nullptr)
                heap.push(head);
        }
        ListNode *dummy = new ListNode(0), *tail = dummy;
        while (!heap.empty()) {
            ListNode *node = heap.top();
            heap.pop();
            tail->next = node;
            tail = node;
            if (node->next != nullptr)
                heap.push(node->next);
        }
        return dummy->next;
    }
};

More Heaps & Priority Queues problems