This problem can be solved using a min-heap of size k.
The min-heap will always store the next unmerged element from each of the k sorted arrays. The element with the smallest value sits at the root of the heap. We build the merged array by repeatedly popping the root from the heap. Each time we pop from the heap, we also push the next element from the same array (if one exists) onto the heap.
When the heap is empty, all elements from all arrays have been merged, and we can return the merged result.
Step 1: Initialize the heap
The first step is to initialize the heap with the first element from each of the k arrays. We iterate over each array and push a tuple containing three values onto the heap:
The element's value
The array's index (which array it came from)
The element's index within that array (starting at 0)
Step 2: Build the merged array
With the heap initialized, we can now build the merged result array. We start by creating an empty result array where we'll append elements in sorted order.
Now, we repeatedly pop the root of the heap, which gives us the element with the smallest value among the unmerged elements from the k arrays. We append this value to our result array.
To ensure that our heap always contains the next unmerged element from each array, after popping an element, we check if there's a next element in the same array. If there is, we push a tuple with the next element's value, the same array index, and the incremented element index onto the heap.
When the heap is empty, all elements from all arrays have been merged, and we can return the result array.
Solution
Test Your Knowledge
Login to take the complexity quiz and track your progress
Complexity Analysis
Time Complexity: O(n * log k) where n is the total number of elements across all input arrays and k is the number of arrays. We iterate over all elements from all arrays. At each iteration, we push and pop elements from the heap, which takes O(log k) time.
Space Complexity: O(k) where k is the number of arrays. We use a min-heap of size k to store the next unmerged element from each of the k arrays.
Your account is free and you can post anonymously if you choose.