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
- 0 ≤ k ≤ 10⁴
- 0 ≤ lists[i].length ≤ 500, at most 10⁴ nodes in total
- -10⁴ ≤ Node.val ≤ 10⁴
- Merging the lists one by one is O(k·N)
Edge cases to test
- k = 0 or all lists empty
- One list
- Lists of very different lengths
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.nextC++
#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
- Kth Largest Element in an Array (Medium)
- Kth Largest Element in a Stream (Easy)
- Find Median from Data Stream (Hard)
- Find K Pairs with Smallest Sums (Medium)
- Heap Sort (Build Heap + Sift Down) (Medium)
- Last Stone Weight (Easy)
- K Closest Points to Origin (Medium)
- Top K Frequent Words (Medium)
- Reorganize String (Medium)
- IPO (Hard)