Hey Mattia,

Say n is the total number of elements in all the streams put together.
The time complexity of your solution is O(n * k). Since you see every
element once and k-1 comparisons are required in the worst case to find
the smallest element.

This approach is actually fine if the streams are infinite in length
and you require say the first 'x' sorted elements.

Another solution to this problem is do a pair wise merging as we do in
merge sort. For example. If there are 8 streams, we make 4 pairs and
merge the 4 pairs into 4 new streams in O(n) time. Then we pair the new
merged streams to get 2 streams and then finally one sorted stream.

Since there will be log k iterations in this approach with each
iteration taking O(n) time.
The complexity in this case is O(n log k). But the problem with this
approach is that you dont get the final list immediately. So it is a
problem when the lists are infinitely long and you want the first 'x'
elements of the sorted list fast.

Thanks,
Hemanth

Reply via email to