Merge K Sorted Arrays
Master this topic with zero to advance depth.
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
Merging the three lists: [1,4,5], [1,3,4], [2,6] results in [1,1,2,3,4,4,5,6].
Empty list.
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.
Detailed Dry Run
| All Elements | Sorted Result |
|---|---|
| [1,4,5, 1,3,4, 2,6] | [1,1,2,3,4,4,5,6] |
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).
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] |
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.
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)]Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.