Practice › Linked List
Merge K Sorted Lists
Hard · Linked List · Asked at Amazon, Google, Meta, Microsoft, Uber
You are given k linked lists, each sorted in non-decreasing order. Merge them into one sorted list and print it.
Input
First line: k. Then, for each list, a line with its length m followed by a line with its m values.
Output
The merged list, space-separated.
Constraints
- 1 ≤ k ≤ 10^4
- 1 ≤ m
- total number of nodes N ≤ 10^5
- −10^9 ≤ values ≤ 10^9
Put the head of every list into a min-heap. Repeatedly take the smallest node, append it to the answer and push its next node — O(N log k). Merging the lists in pairs, like merge sort, also gives O(N log k).
Example 1
Input
3 3 1 4 5 3 1 3 4 2 2 6
Output
1 1 2 3 4 4 5 6
Example 2
Input
1 1 7
Output
7
Hints
- The next node of the answer is the smallest of the k current heads.
- A min-heap gives that smallest head in O(log k).
- After taking a node, push the next node of its list.
Approach
Push the head of every list into a min-heap ordered by value. Pop the smallest node, append it to the result, and push its successor if there is one. Each of the N nodes is pushed and popped once, so the work is O(N log k) — much better than merging the lists one by one, which can cost O(N·k).
Complexity: O(N log k) time · O(k) heap space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
long long val;
Node *next = nullptr;
Node(long long v) : val(v) {}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int k;
cin >> k;
auto cmp = [](Node *a, Node *b) { return a->val > b->val; };
priority_queue<Node *, vector<Node *>, decltype(cmp)> pq(cmp);
for (int i = 0; i < k; i++) {
int m;
cin >> m;
Node dummy(0), *t = &dummy;
for (int j = 0; j < m; j++) {
long long x;
cin >> x;
t = t->next = new Node(x);
}
pq.push(dummy.next);
}
Node res(0), *tail = &res;
while (!pq.empty()) {
Node *top = pq.top();
pq.pop();
tail = tail->next = top;
if (top->next) pq.push(top->next);
}
for (Node *p = res.next; p; p = p->next) cout << p->val << (p->next ? " " : "\n");
return 0;
}Python solution
import heapq
import sys
class Node:
def __init__(self, val):
self.val, self.next = val, None
data = list(map(int, sys.stdin.read().split()))
k, p = data[0], 1
heap = []
for i in range(k):
m = data[p]
dummy = tail = Node(0)
for v in data[p + 1 : p + 1 + m]:
tail.next = Node(v)
tail = tail.next
p += 1 + m
heapq.heappush(heap, (dummy.next.val, i, dummy.next))
res = tail = Node(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))
out, q = [], res.next
while q:
out.append(q.val)
q = q.next
print(*out)Java solution
import java.io.*;
import java.util.*;
public class Main {
static class Node {
long val;
Node next;
Node(long v) { val = v; }
}
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int k = (int) in.nval;
PriorityQueue<Node> pq = new PriorityQueue<>((a, b) -> Long.compare(a.val, b.val));
for (int i = 0; i < k; i++) {
in.nextToken();
int m = (int) in.nval;
Node dummy = new Node(0), t = dummy;
for (int j = 0; j < m; j++) {
in.nextToken();
t = t.next = new Node((long) in.nval);
}
pq.add(dummy.next);
}
Node res = new Node(0), tail = res;
while (!pq.isEmpty()) {
Node top = pq.poll();
tail = tail.next = top;
if (top.next != null) pq.add(top.next);
}
StringBuilder sb = new StringBuilder();
for (Node p = res.next; p != null; p = p.next) sb.append(p.val).append(p.next != null ? " " : "\n");
System.out.print(sb);
}
}