Given M sorted lists of variable length, merge them efficiently in sorted order.

For example,

Input:  4 sorted lists of variable length
 
[10, 20, 30, 40]
[15, 25, 35]
[27, 29, 37, 48, 93]
[32, 33]
 
Output:
 
[10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 40, 48, 93]

Practice this problem

A simple solution would be to create an auxiliary array containing all lists’ elements (order doesn’t matter). Then use an efficient sorting algorithm to sort the array in ascending order and print the elements. The worst-case time complexity of this approach will be O(N.log(N)), where N is the total number of elements present in all lists. Also, this approach does not take advantage of the fact that each list is already sorted.

 
We can easily solve this problem in O(N.log(M)) time by using a min-heap. The idea is to construct a min-heap of size M and insert the first element of each list into it. Then pop the root element (minimum element) from the heap and insert the next element from the “same” list as the popped element. Repeat this process till the heap is exhausted. Depending upon the requirement, either print the popped element or store it in an auxiliary array.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

10 15 20 25 27 29 30 32 33 35 37 40 48 93

Java


Download  Run Code

Output:

10 15 20 25 27 29 30 32 33 35 37 40 48 93

Python


Download  Run Code

Output:

10 15 20 25 27 29 30 32 33 35 37 40 48 93

The time complexity of the above solution is O(N.log(M)) as the heap has size M, and we pop and push exactly N times, where N is the total number of elements. Note that each pop/push operation takes O(log(M)) time.