![]() |
VOOZH | about |
Given k sorted arrays of possibly different sizes, merge them and print the sorted output.
Examples:
Input: k = 3
arr[][] = { {1, 3},
{2, 4, 6},
{0, 9, 10, 11}} ;
Output: 0 1 2 3 4 6 9 10 11
Input: k = 2
arr[][] = { {1, 3, 20},
{2, 4, 6}} ;
Output: 1 2 3 4 6 20
We have discussed a solution that works for all arrays of the same size in Merge k sorted arrays
A simple solution is to create an output array and one by one copy all k arrays to it. Finally, sort the output array. This approach takes O(N Log N) time where N is the count of all elements.
An efficient solution is to use a heap data structure. The time complexity of the heap-based solution is O(N Log k).
1. Create an output array.
2. Create a min-heap of size k and insert 1st element in all the arrays into the heap
3. Repeat the following steps while the priority queue is not empty.
.....a) Remove the minimum element from the heap (minimum is always at the root) and store it in the output array.
.....b) Insert the next element from the array from which the element is extracted. If the array doesn’t have any more elements, then do nothing.
Below is the implementation of the above approach:
Merged array is 1 2 6 9 12 23 34 90 2000
Time Complexity: O(N log k) Here N is total number of elements in all input arrays.
Auxiliary Space: O(k)