Merge K sorted linked lists
Given K sorted linked lists of size N each, merge them and print the sorted output.
Example:
Input: k = 3, n = 4
list1 = 1->3->5->7->NULL
list2 = 2->4->6->8->NULL
list3 = 0->9->10->11
Output:
0->1->2->3->4->5->6->7->8->9->10->11
Method 1 (Simple)
A Simple Solution is to initialize result as first list. Now traverse all lists starting from second list. Insert every node of currently traversed list into result in a sorted way. Time complexity of this solution is O(N2) where N is total number of nodes, i.e., N = kn.
A Better solution is to use Min Heap based solution which is discussed here for arrays. Time complexity of this solution would be O(nk Log k)
In this post, Divide and Conquer approach is discussed. This approach doesn’t require extra space for heap and works in O(nk Log k)
We already know that merging of two linked lists can be done in O(n) time and O(1) space (For arrays O(n) space is required). The idea is to pair up K lists and merge each pair in linear time using O(1) space. After first cycle, K/2 lists are left each of size 2*N. After second cycle, K/4 lists are left each of size 4*N and so on. We repeat the procedure until we have only one list left.
Output :
0 1 2 3 4 5 6 7 8 9 10 11
Time Complexity of above algorithm is O(nklogk) as outer while loop in function mergeKLists() runs log k times and every time we are processing nk elements.
No comments:
Post a Comment