Python Program To Merge K Sorted Linked Lists - Set 1
Last Updated :
15 Feb, 2023
Given K sorted linked lists of size N each, merge them and print the sorted output.
Examples:
Input: k = 3, n = 4
list1 = 1->3->5->7->NULL
list2 = 2->4->6->8->NULL
list3 = 0->9->10->11->NULL
Output: 0->1->2->3->4->5->6->7->8->9->10->11
Merged lists in a sorted order
where every element is greater
than the previous element.
Input: k = 3, n = 3
list1 = 1->3->7->NULL
list2 = 2->4->8->NULL
list3 = 9->10->11->NULL
Output: 1->2->3->4->7->8->9->10->11
Merged lists in a sorted order
where every element is greater
than the previous element.
Method 1 (Simple):
Approach:
A Simple Solution is to initialize the result as the first list. Now traverse all lists starting from the second list. Insert every node of the currently traversed list into result in a sorted way.
Python3
# Python3 program to merge k
# sorted arrays of size n each
# A Linked List node
class Node:
def __init__(self, x):
self.data = x
self.next = None
# Function to print nodes in a given
# linked list
def printList(node):
while (node != None):
print(node.data,
end = " ")
node = node.next
# The main function that takes an
# array of lists arr[0..last] and
# generates the sorted output
def mergeKLists(arr, last):
# Traverse from second
# list to last
for i in range(1, last + 1):
while (True):
# head of both the lists,
# 0 and ith list.
head_0 = arr[0]
head_i = arr[i]
# Break if list ended
if (head_i == None):
break
# Smaller than first
# element
if (head_0.data >=
head_i.data):
arr[i] = head_i.next
head_i.next = head_0
arr[0] = head_i
else:
# Traverse the first list
while (head_0.next != None):
# Smaller than next
# element
if (head_0.next.data >=
head_i.data):
arr[i] = head_i.next
head_i.next = head_0.next
head_0.next = head_i
break
# go to next node
head_0 = head_0.next
# if last node
if (head_0.next == None):
arr[i] = head_i.next
head_i.next = None
head_0.next = head_i
head_0.next.next = None
break
return arr[0]
# Driver code
if __name__ == '__main__':
# Number of linked
# lists
k = 3
# Number of elements
# in each list
n = 4
# an array of pointers
# storing the head nodes
# of the linked lists
arr = [None for i in range(k)]
arr[0] = Node(1)
arr[0].next = Node(3)
arr[0].next.next = Node(5)
arr[0].next.next.next = Node(7)
arr[1] = Node(2)
arr[1].next = Node(4)
arr[1].next.next = Node(6)
arr[1].next.next.next = Node(8)
arr[2] = Node(0)
arr[2].next = Node(9)
arr[2].next.next = Node(10)
arr[2].next.next.next = Node(11)
# Merge all lists
head = mergeKLists(arr, k - 1)
printList(head)
# This code is contributed by Mohit Kumar 29
Output:
0 1 2 3 4 5 6 7 8 9 10 11
Complexity Analysis:
- Time complexity: O(nk2)
- Auxiliary Space: O(1).
As no extra space is required.
Method 2: Min Heap.
A Better solution is to use Min Heap-based solution which is discussed here for arrays. The time complexity of this solution would be O(nk Log k)
Method 3: Divide and Conquer.
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)
It is known that merging of two linked lists can be done in O(n) time and O(n) space.
- The idea is to pair up K lists and merge each pair in linear time using O(n) space.
- After the first cycle, K/2 lists are left each of size 2*N. After the second cycle, K/4 lists are left each of size 4*N and so on.
- Repeat the procedure until we have only one list left.
Below is the implementation of the above idea.
Python3
# Python3 program to merge k sorted
# arrays of size n each
# A Linked List node
class Node:
def __init__(self):
self.data = 0
self.next = None
# Function to print nodes in a
# given linked list
def printList(node):
while (node != None):
print(node.data, end = ' ')
node = node.next
# Takes two lists sorted in increasing order,
# and merge their nodes together to make one
# big sorted list. Below function takes
# O(Log n) extra space for recursive calls,
# but it can be easily modified to work with
# same time and O(1) extra space
def SortedMerge(a, b):
result = None
# Base cases
if (a == None):
return(b)
elif (b == None):
return(a)
# Pick either a or b, and recur
if (a.data <= b.data):
result = a
result.next =
SortedMerge(a.next, b)
else:
result = b
result.next =
SortedMerge(a, b.next)
return result
# The main function that takes an array
# of lists arr[0..last] and generates
# the sorted output
def mergeKLists(arr, last):
# Repeat until only one list is left
while (last != 0):
i = 0
j = last
# (i, j) forms a pair
while (i < j):
# Merge List i with List j and store
# merged list in List i
arr[i] = SortedMerge(arr[i], arr[j])
# Consider next pair
i += 1
j -= 1
# If all pairs are merged, update last
if (i >= j):
last = j
return arr[0]
# Utility function to create a new node.
def newNode(data):
temp = Node()
temp.data = data
temp.next = None
return temp
# Driver code
if __name__=='__main__':
# Number of linked lists
k = 3
# Number of elements in each list
n = 4
# An array of pointers storing the
# head nodes of the linked lists
arr = [0 for i in range(k)]
arr[0] = newNode(1)
arr[0].next = newNode(3)
arr[0].next.next = newNode(5)
arr[0].next.next.next = newNode(7)
arr[1] = newNode(2)
arr[1].next = newNode(4)
arr[1].next.next = newNode(6)
arr[1].next.next.next = newNode(8)
arr[2] = newNode(0)
arr[2].next = newNode(9)
arr[2].next.next = newNode(10)
arr[2].next.next.next = newNode(11)
# Merge all lists
head = mergeKLists(arr, k - 1)
printList(head)
# This code is contributed by rutvik_56
Output:
0 1 2 3 4 5 6 7 8 9 10 11
Complexity Analysis:
Assuming N(n*k) is the total number of nodes, n is the size of each linked list, and k is the total number of linked lists.
- Time Complexity: O(N*log k) or O(n*k*log k)
As outer while loop in function mergeKLists() runs log k times and every time it processes n*k elements. - Auxiliary Space: O(N) or O(n*k)
Because recursion is used in SortedMerge() and to merge the final 2 linked lists of size N/2, N recursive calls will be made.
Please refer complete article on Merge K sorted linked lists | Set 1 for more details!
Similar Reads
Python Program For Merge Sort Of Linked Lists Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible. Let the head be the first node of the linked list to be sorted and headRe
6 min read
Python Program To Merge Two Sorted Lists (In-Place) Given two sorted lists, merge them so as to produce a combined sorted list (without using extra space).Examples: Input: head1: 5->7->9 head2: 4->6->8 Output: 4->5->6->7->8->9 Explanation: The output list is in sorted order. Input: head1: 1->3->5->7 head2: 2->4 Output: 1->2->3->4->5->7 Explanation: T
5 min read
Python Program For Merge Sort For Doubly Linked List Given a doubly linked list, write a function to sort the doubly linked list in increasing order using merge sort.For example, the following doubly linked list should be changed to 24810 Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Merge sort for singly linked l
3 min read
Python Program For Finding Intersection Of Two Sorted Linked Lists Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory â the original lists should not be changed. Example: Input: First linked list: 1->2->3->4->6 Second linked list be 2->4->6->8, Ou
4 min read
Python Program To Delete Middle Of Linked List Given a singly linked list, delete the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the linked list should be modified to 1->2->4->5 If there are even nodes, then there would be two middle nodes, we need to delete the second middle element. For example, if g
4 min read
Python program to insert an element into sorted list Inserting an element into a sorted list while maintaining the order is a common task in Python. It can be efficiently performed using built-in methods or custom logic. In this article, we will explore different approaches to achieve this.Using bisect.insort bisect module provides the insort function
2 min read