Merge k Sorted Arrays
Merge k Sorted Arrays is a medium heaps problem solved with the merge k sorted pattern.
The best approach, optimal (min-heap of array heads), runs in O(N log k) time and O(k) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from concatenate and sort up.
Problem
Given k sorted arrays, merge them into one sorted array.
Examples
Example 1
- Input
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]- Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 2
- Input
arr = [[1, 5], [2, 3], [4, 9]]- Output
[1, 2, 3, 4, 5, 9]
Constraints
1 <= k <= 100; each array has length k.- Each array is sorted.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 8 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Concatenate and sort | O(N log N) | O(N) |
| Optimal (min-heap of array heads) | O(N log k) | O(k) |
1Concatenate and sort
O(N log N)O(N)Put everything into one list and sort it.
- Add all elements; Collections.sort.
class Solution {
public static ArrayList<Integer> mergeKArrays(int[][] arr, int K) {
ArrayList<Integer> out = new ArrayList<>();
for (int[] row : arr) for (int x : row) out.add(x);
Collections.sort(out);
return out;
}
}class Solution:
@staticmethod
def mergeKArrays(arr: List[List[int]], K: int) -> List[int]:
out = []
for row in arr:
for x in row:
out.append(x)
out.sort()
return outclass Solution {
public:
static vector<int> mergeKArrays(vector<vector<int>>& arr, int K) {
vector<int> out;
for (auto& row : arr) for (int x : row) out.push_back(x);
sort(out.begin(), out.end());
return out;
}
};function mergeKArrays(arr, K) {
const out = [];
for (const row of arr) for (const x of row) out.push(x);
out.sort((a, b) => a - b);
return out;
}2Optimal (min-heap of array heads)
O(N log k)O(k)Besides the output.Keep one entry per array in a min-heap: {value, row, col}. Poll the smallest, append it, and push the next element of the same row.
- Offer {arr[r][0], r, 0} for each row.
- Poll; append; if col + 1 < len, offer the next element.
class Solution {
public static ArrayList<Integer> mergeKArrays(int[][] arr, int K) {
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0]));
for (int r = 0; r < arr.length; r++) if (arr[r].length > 0) heap.offer(new int[] { arr[r][0], r, 0 });
ArrayList<Integer> out = new ArrayList<>();
while (!heap.isEmpty()) {
int[] e = heap.poll();
out.add(e[0]);
int r = e[1], c = e[2] + 1;
if (c < arr[r].length) heap.offer(new int[] { arr[r][c], r, c });
}
return out;
}
}class Solution:
@staticmethod
def mergeKArrays(arr: List[List[int]], K: int) -> List[int]:
heap = []
for r in range(len(arr)):
if len(arr[r]) > 0:
heapq.heappush(heap, (arr[r][0], r, 0))
out = []
while heap:
val, r, c = heapq.heappop(heap)
out.append(val)
c += 1
if c < len(arr[r]):
heapq.heappush(heap, (arr[r][c], r, c))
return outclass Solution {
public:
static vector<int> mergeKArrays(vector<vector<int>>& arr, int K) {
priority_queue<array<int, 3>, vector<array<int, 3>>, greater<array<int, 3>>> heap;
for (int r = 0; r < (int)arr.size(); r++) if (arr[r].size() > 0) heap.push({arr[r][0], r, 0});
vector<int> out;
while (!heap.empty()) {
array<int, 3> e = heap.top();
heap.pop();
out.push_back(e[0]);
int r = e[1], c = e[2] + 1;
if (c < (int)arr[r].size()) heap.push({arr[r][c], r, c});
}
return out;
}
};class MinHeap {
constructor(cmp = (a, b) => a - b) { this.a = []; this.cmp = cmp; }
size() { return this.a.length; }
isEmpty() { return this.a.length === 0; }
peek() { return this.a[0]; }
push(x) {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (this.cmp(a[i], a[p]) >= 0) break;
[a[i], a[p]] = [a[p], a[i]];
i = p;
}
}
pop() {
const a = this.a, top = a[0], last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
while (true) {
const l = 2 * i + 1, r = l + 1;
let m = i;
if (l < a.length && this.cmp(a[l], a[m]) < 0) m = l;
if (r < a.length && this.cmp(a[r], a[m]) < 0) m = r;
if (m === i) break;
[a[i], a[m]] = [a[m], a[i]];
i = m;
}
}
return top;
}
}
function mergeKArrays(arr, K) {
const heap = new MinHeap((a, b) => a[0] - b[0]);
for (let r = 0; r < arr.length; r++) if (arr[r].length > 0) heap.push([arr[r][0], r, 0]);
const out = [];
while (!heap.isEmpty()) {
const e = heap.pop();
out.push(e[0]);
const r = e[1], c = e[2] + 1;
if (c < arr[r].length) heap.push([arr[r][c], r, c]);
}
return out;
}Edge cases to test
- Arrays of different lengths (the heap method still works)
Hints
Hint 1
Store (value, array index, element index) in the heap so you know what to push next.
FAQ
What is the best time complexity for Merge k Sorted Arrays?
Optimal (min-heap of array heads) runs in O(N log k) time and O(k) extra space.
Which pattern does Merge k Sorted Arrays use?
It is a heaps problem that uses the merge k sorted pattern. Other problems with the same pattern: Merge k Sorted Lists, Design Twitter, Smallest Range Covering Elements from K Lists.
Is there a brute force solution for Merge k Sorted Arrays?
Yes. Concatenate and sort takes O(N log N) time and O(N) space. Put everything into one list and sort it.
Which edge cases should I test for Merge k Sorted Arrays?
Arrays of different lengths (the heap method still works).