# Merge K Sorted Linked Lists using Min Heap

The efficient merging of K-sorted linked lists is a typical challenge in computer science and software development. This assignment entails integrating various linked lists that have already been sorted in ascending order into a single sorted linked list. Using a Min Heap data structure is one of the more efficient ways to handle this problem. In this article, we'll look at the Min Heap technique for merging K-sorted linked lists, as well as its implementation and time and space difficulties.

### Merge K Sorted Linked Lists: An Introduction

When dealing with K-sorted linked lists, a simple but time-consuming solution is to merge pairs of lists until they are all merged into a single list. However, this approach exhibits a temporal complexity of O(N^2), where N represents the overall number of nodes across all lists.

• Conversely, the Min Heap method offers a more efficient solution, reducing the time complexity to O(N log K), where N signifies the total number of nodes, and K denotes the number of linked lists.

Understanding Min Heap:

A Min Heap is a complete binary tree wherein each node's value is equal to or smaller than the values of its children. It is frequently expressed as an array, which allows for quick insertion and extraction of the minimal member. In this case, the head nodes of the K-linked lists will be stored in a Min Heap.

### Algorithm: Merge K Sorted Linked Lists using Min Heap

Input: K sorted linked lists.

Output: A single sorted linked list containing all elements from the K input lists.

Steps:

Step 1: Initialize an empty Min Heap.

• The Min Heap will store tuples consisting of the node value and a reference to the node itself.
• The nodes will be compared based on their values.

Step 2: Traverse through all K-linked lists and insert their head nodes into the Min Heap.

• For each linked list in the input set:
• If the head node exists (i.e., it's None), insert a tuple (node. val, node) into the Min Heap.
• Move to the next node in the linked list.

Step 3: Initialize an empty result-linked list to store the merged output.

• It will be used to create the final sorted linked list.

Step 4: While the Min Heap is not empty:

• Extract the minimum node from the Min Heap.
• Append the extracted node to the result-linked list.
• Move the pointer of the extracted node to its next node and insert it back into the Min Heap if it exists.

Step 5: Return the head of the result-linked list.

• It will be the head of the merged sorted linked list.

Example

Let's consider three sorted linked lists:

List 1: 1 -> 4 -> 5

List 2: 1 -> 3 -> 4

List 3: 2 -> 6

We'll apply the merging algorithm using a min-heap to combine these linked lists into a single sorted list.

Step 1: Initialize a Min Heap

We start by creating an empty min heap.

Step 2: Populate the Min Heap

Insert the head nodes of the three lists into the min heap.

Heap:

Step 3: Merge Process

While the min heap is not empty:

1. Extract the minimum element from the min heap (which is 1 from List 1).
2. Add this minimum element (1) to the result linked list.
3. Push the next node from List 1 into the min heap (which is 4).

Heap:

Continue this process:

1. Extract 1 from List 2.
2. Add 1 to the result-linked list.
3. Push the next node from List 2 into the min heap (which is 3).

Heap:

1. Extract 2 from List 3.
2. Add 2 to the result linked list.
3. Push the next node from List 3 into the min heap (which is 6).

Heap:

1. Extract 3 from List 2.
2. Add 3 to the result linked list.
3. Push the next node from List 2 into the min heap (which is 4).

Heap:

1. Extract 4 from List 1.
2. Add 4 to the result linked list.
3. Push the next node from List 1 into the min heap (which is 5).

Heap:

1. Extract 4 from List 2.
2. Add 4 to the result linked list.
3. Push the next node from List 2 into the min heap (which is None).

Heap:

1. Extract 5 from List 1.
2. Add 5 to the result linked list.
3. Push the next node from List 1 into the min heap (which is None).

Heap:

1. Extract 6 from List 3.
2. Add 6 to the result linked list.
3. Push the next node from List 3 into the min heap (which is None).

Heap: (Empty)

The result linked list after merging the three sorted lists would be: 1 -> 1 -> 2 -> 3 -> 4 -> 4 -> 5 -> 6

### Implementation

Output:

Explanation

ListNode Class:

• The ListNode class represents a node in a linked list.
• It contains two attributes: val (the value of the node) and next (a reference to the next node in the linked list).

Custom Comparison Method:

• The key addition in this version is the __lt__ method within the ListNode class.
• __lt__ (less than) is a special method in Python that defines the behavior of the < operator for custom objects.
• By implementing __lt__, it enables instances of ListNode to be compared based on their val attribute. It is essential for proper comparisons when using the heapq module.

mergeKLists Function:

• The mergeKLists function takes a list of sorted linked lists as input and merges them into a single sorted linked list.
• It utilizes a min heap to merge the lists efficiently.
• pushNode function adds a node to the min heap if it exists.

• This function creates a linked list from a list of values.

Sample Input and Output:

• The list variable contains three sample-sorted linked lists.
• The mergeKLists function is called with these lists to merge them.
• The merged sorted linked list is then traversed to collect its values and display them as output.

Time Complexity

Building the Heap:

Inserting the head nodes of all K lists into the min heap takes O(K log K) time.

Merging:

• Each node will be added to and removed from the heap exactly once. The maximum number of nodes in the heap at any point will be K.
• The total operations to merge all nodes is O(N log K), where N is the total number of nodes across all linked lists.

Overall:

The time complexity for building the heap and merging the lists is O(N log K).

Space Complexity

Heap Space:

The space required for the min heap will be O(K) since, at most, K nodes will be in the heap at any time during the merging process.

The merged linked list will require additional space equivalent to the total number of nodes, which is O(N).

Overall:

The space complexity will be O(max(N, K)), considering the space required for the heap and the merged linked list.

Summary

Time Complexity: O(N log K)

Space Complexity: O(max(N, K))

## Conclusion

When merging K-sorted linked lists, the Min Heap technique considerably decreases temporal complexity when compared to alternative approaches. We efficiently combine the lists in a sorted way by utilizing the capabilities of the Min Heap data structure, demonstrating the significance of selecting the correct data structures and methods in problem-solving scenarios.