Merge “K” sorted arrays
Pattern: K-way merge
Put the first value of every array into a min heap with its array and index. Pop the smallest, output it, and push the next value from the same array. With k arrays of k values each, that is O(k² log k).
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
Given k sorted arrays of k values each, return one sorted array holding all of them.
The catalogue has no practice link for this one.
Think first
- Where is the smallest value of all?
- After taking it, what is the next candidate from its array?
- How many candidates are there at once?
Hints
Brute force, and why it fails
Join everything and sort: O(k² log k²). Merging the arrays one after another: O(k³).
The key insight
The heap always holds each array's current front, and the smallest front is the next output.
Dry run
| heap | 1 4 7 |
|---|
arrays [1, 2, 3], [4, 5, 6], [7, 8, 9]. The heap starts with 1, 4, 7.
The plan
heap = [(arr[i][0], i, 0)]
while heap:
(v, i, j) = pop; output v
if j + 1 < len(arr[i]): push (arr[i][j + 1], i, j + 1)
Complexity
- Time
O(N log k), N = k²- Space
O(k) besides the output
Every value goes through the heap of at most k items once.
Edge cases
- k = 1.
- Equal values in several arrays.
- Negative values.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public int[] mergeKArrays(int[][] arr) {
PriorityQueue<int[]> heap = new PriorityQueue<>((x, y) -> Integer.compare(x[0], y[0])); // {value, array, index}
int total = 0;
for (int i = 0; i < arr.length; i++) {
total += arr[i].length;
if (arr[i].length > 0) heap.add(new int[]{arr[i][0], i, 0}); // each array's smallest
}
int[] out = new int[total];
for (int t = 0; t < total; t++) {
int[] top = heap.poll();
out[t] = top[0];
int i = top[1], j = top[2] + 1;
if (j < arr[i].length) heap.add(new int[]{arr[i][j], i, j}); // replace it with the next from its array
}
return out;
}
}C++
class Solution {
public:
vector<int> mergeKArrays(vector<vector<int>>& arr) {
typedef pair<int, pair<int, int>> Item; // {value, {array, index}}
priority_queue<Item, vector<Item>, greater<Item>> heap;
for (int i = 0; i < static_cast<int>(arr.size()); i++)
if (!arr[i].empty()) heap.push(make_pair(arr[i][0], make_pair(i, 0))); // each array's smallest
vector<int> out;
while (!heap.empty()) {
Item top = heap.top();
heap.pop();
out.push_back(top.first);
int i = top.second.first, j = top.second.second + 1;
if (j < static_cast<int>(arr[i].size())) heap.push(make_pair(arr[i][j], make_pair(i, j))); // its next
}
return out;
}
};Python
import heapq
class Solution:
def mergeKArrays(self, arr: list[list[int]]) -> list[int]:
heap = [(a[0], i, 0) for i, a in enumerate(arr) if a] # each array's smallest
heapq.heapify(heap)
out = []
while heap:
v, i, j = heapq.heappop(heap)
out.append(v)
if j + 1 < len(arr[i]):
heapq.heappush(heap, (arr[i][j + 1], i, j + 1)) # replace it with the next from its array
return outCommon mistakes
- Pushing all values at once.
- Forgetting which array a popped value came from.