Given K sorted linked lists of size N each, merge them and print the sorted output.
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
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.
Below is C++ implementation of the above idea.
0 1 2 3 4 5 6 7 8 9 10 11
Time Complexity of above algorithm is O(nk logk) as outer while loop in function mergeKLists() runs log k times and every time we are processing nk elements.
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Sorted merge of two sorted doubly circular linked lists
- Merge two sorted linked lists
- Merge k sorted linked lists | Set 2 (Using Min Heap)
- Merge two sorted linked lists such that merged list is in reverse order
- Merge two sorted lists (in-place)
- Merge Sort for Linked Lists
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
- In-place Merge two linked lists without changing links of first list
- Merge two sorted linked list without duplicates
- Intersection of two Sorted Linked Lists
- Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
- Merge two sorted arrays
- Sorted merge in one array