Merge k Sorted Arrays

Medium Heaps Merge K Sorted Original on GeeksforGeeks

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, 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.

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 Java code.

ApproachTimeSpace
Concatenate and sortO(N log N)O(N)
Optimal (min-heap of array heads)O(N log k)O(k)

1Concatenate and sort

TimeO(N log N)
SpaceO(N)

Put everything into one list and sort it.

  1. Add all elements; Collections.sort.
Java
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;
    }
}

2Optimal (min-heap of array heads)

TimeO(N log k)
SpaceO(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.

  1. Offer {arr[r][0], r, 0} for each row.
  2. Poll; append; if col + 1 < len, offer the next element.
Java
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;
    }
}

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.

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).