Interview Question
Country: United States
A different approach:
**Benefit: We do not need to rearrange resultant array again and again as we do in conventional way merging first 2 then 3rd then fourth.... and so on....
-Have k integer index to traverse K sorted arrays
[index1,index2,index3,index4.......indexk]
-Initiate all with first element of respective sorted arrays.
[index1=array1's first index ,index2=array2's first index.......indexk=arrayk's first index ]
-Now compare elements from all traversing indexes [index1,index2,index3,index4.......indexk] in respective array.
-Which ever element is smallest.... copy that element to new mergeSortedArray[] and increase the traversing index by 1.
-keep repeating above steps unless all the arrays are not traversed.
While this result would work, its best to use a priority queue/heap to implement the comparison between K elements. Otherwise, you have to go through K*N elements for each looking through K elements to find the smallest yielding an O(N*K^2) solution. A heap will reduce this to O(N*K lg K).
I'm not sure why you are using a heap? Is this really needed?
What about if you do:
1. while there is more elements in any of the k arrays -> O(nk)
2. iterate over the first element of each k arrays and select the minimum -> O(k)
3. remove this value from the array and put it in the result array -> O(1)
At the end it would be O(nk^2) right? The good news is that you don't need the extra heap
Using the given algorithm. The first merge takes 2n, the second 3n, the third 4n...
- Some guy July 21, 2013We are then given a summation 2n + 3n + 4n + 5n +6n + ... + kn
Which is equal to n*(2+3+4+...k)
Which is equal to n*(k*(k+1)/2 - 1)
Which implies a runtime of n*k^2
A faster solution would be to not merge successively. Merge all n until you get k/2 * 2n. Like merge sort, we merge evenly sized arrays at every step. This would yield a solution with the complexity of mergesort with K elements which is n*k log k. The amount of space is O(k*n)
Given K arrays with N elements each. First take the smallest value of each array and put it into the heap. Keep track of which array each value came from. Then pop the smallest value off the array and put this into the final array. Then insert another value from the array the pop came from. The runtime for this is also k*n*log k since we have to go through all k*n elements. Insertion into a k size heap is log k and pop is O(1).