Introduction
Merge K Sorted Lists means combining multiple sorted linked lists into one sorted linked list.
The task is to:
- compare nodes from all lists
- select smallest node
- maintain sorted order
Example:
Input:
List1:
1 -> 4 -> 7
List2:
2 -> 5 -> 8
List3:
3 -> 6 -> 9
Output:1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9
Explanation:
Smallest node is selected from all lists at every step.Final linked list remains sorted.This problem is one of the most important applications of:
Min Heap / Priority QueueConstraints
0 <= Total Nodes <= 10^5-10^9 <= Node Value <= 10^9
Approach 1 : Brute Force (Using Array)
Explanations:
Explanation:
The idea is:
- store all linked list values
- sort entire array
- rebuild linked list
Steps:
- Traverse all lists.
- Store all values.
- Sort array.
- Create merged list.
This approach works but:
- sorting becomes expensive
So Min Heap approach is preferred.
Dry Run
Input:1 -> 4 -> 7
2 -> 5 -> 8
3 -> 6 -> 9
Array:
[1,4,7,2,5,8,3,6,9]
Sorted:
[1,2,3,4,5,6,7,8,9]
Output:
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9
Practice :
Complexity Analysis :
Time Complexity:- O(n log n)Explanation :
Sorting all elements takes extra time.
Space Complexity:- O(n)
Explanation :
Extra array is used.
Approach 2 : Optimal Solution(Using Min Heap)
Explanations:
Explanation:
This is the most optimized and interview-preferred solution.
The idea is:
- insert first node from each list
- use Min Heap to get smallest node
- insert next node from selected list
This keeps merged list sorted efficiently.
Dry Run
Input:
1 -> 4 -> 7
2 -> 5 -> 8
3 -> 6 -> 9
Heap:
1 2 3
Pick:
1
Insert:
4
Heap:
2 3 4
Continue process.
Output:1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9
Practice :