Merge k Sorted Lists
📌 Problem Idea
You are given K sorted lists.
You want to merge them into one final sorted list.
Instead of merging two lists at a time (which can be slow), you use a min-heap to efficiently find the smallest element among all current nodes.
⚙️ Naive Approach
Concatenate all lists into one.
Sort the combined list.
❌ Time Complexity: O(N log N)
(where N = total number of nodes)
✅ Optimized Approach — Using a Min-Heap (Priority Queue)
Idea
Maintain a min-heap containing the first node (smallest element) from each of the k lists.
Repeatedly:
Extract the minimum node from the heap.
Append it to the result list.
Insert the next node from the same list into the heap (if it exists).
This way, the smallest available element is always efficiently found in O(log k) time.
🧠Algorithm
Input:
k
sorted linked lists
Output:
A single sorted linked list
Steps:
Create a min-heap (using array or priority queue).
Insert the head node of each linked list into the heap (store value + pointer).
Initialize an empty result list (using dummy node).
While the heap is not empty:
Extract the smallest node (min).
Append it to the result list.
If the extracted node has a
next
, pushnext
into the heap.
Return the merged list starting from
dummy->next
.
Complexity
Each insertion and extraction in heap: O(log k)
For all N nodes: O(N log k)
Space: O(k) for heap
📚 Steps to Solve
-
Create a min-heap.
-
Each element of the heap will be a pointer to a node.
-
Heap is organized by node->data value (smallest data at top).
-
-
Insert the first node of each list into the heap.
-
While heap is not empty:
-
Extract the smallest node from the heap (this is the smallest value available).
-
Add this node to the result list.
-
If this extracted node has a next node, insert the next node into the heap.
-
-
Repeat until all nodes are processed.
🔥 Algorithm
Comments
Post a Comment