Merge K Sorted Arrays
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Arrays & Hashing.
Merge K Sorted Arrays
Merging multiple sorted arrays can be done efficiently using a Min-Heap. By keeping the current element of each array in the heap, we can always extract the smallest element in O(log K) time. Alternatively, Divide and Conquer can merge them in pairs.
You are given k sorted arrays. Merge all the arrays into one sorted array and return it.
Visual Representation
Arrays:
[1, 4, 5]
[1, 3, 4]
[2, 6]
Heap state (Min-Heap of elements from each array):
[1, 1, 2] -> Pop 1
[4, 1, 2] -> Pop 1
[4, 3, 2] -> Pop 2
...
Result: [1, 1, 2, 3, 4, 4, 5, 6]Examples
Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Merging the three lists: [1,4,5], [1,3,4], [2,6] results in [1,1,2,3,4,4,5,6].
Input: lists = []
Output: []
Empty list.
Approach 1
Level I: Brute Force (Flatten and Sort)
Intuition
Collect all elements from all K arrays into a single list, sort that list, and return it. This is simple but doesn't take advantage of the fact that each individual array is already sorted.
⏱ O(N log N) where N is the total number of elements.💾 O(N) to store all elements in a new list.
Detailed Dry Run
| All Elements | Sorted Result |
|---|---|
| [1,4,5, 1,3,4, 2,6] | [1,1,2,3,4,4,5,6] |
Approach 2
Level II: Better Solution (Divide and Conquer)
Intuition
Merge the K arrays in pairs. In the first pass, merge array 1 with 2, 3 with 4, etc. Repeat this process until only one sorted array remains. This reduces the number of arrays logarithmically (log K).
⏱ O(N log K) where N is total elements and K is number of arrays.💾 O(N) for the result array.
Detailed Dry Run
| Step | Pairs Merged | Result Arrays |
|---|---|---|
| 1 | [1,4,5] + [1,3,4] | [1,1,3,4,4,5] |
| 1 | [2,6] | [2,6] |
| 2 | [1,1,3,4,4,5] + [2,6] | [1,1,2,3,4,4,5,6] |
Approach 3
Level III: Optimal Solution (Min Heap)
Intuition
Use a Min-Heap to store the first element of each array along with its source array index and element index. Repeatedly extract the minimum element and insert the next element from the same array into the heap.
⏱ O(N log K) where N is total elements and K is number of arrays.💾 O(K) for the Min-Heap.
Detailed Dry Run
Min-Heap Merge Process
arrays = [[1, 4], [1, 3], [2, 6]]Heap (val, array_idx, element_idx):
1. Push roots: [(1,0,0), (1,1,0), (2,2,0)]
2. Pop (1,0,0) -> Res: [1]. Push (4,0,1). Heap: [(1,1,0), (2,2,0), (4,0,1)]
3. Pop (1,1,0) -> Res: [1, 1]. Push (3,1,1). Heap: [(2,2,0), (3,1,1), (4,0,1)]Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.