Introduction
Merge K Sorted Lists means:
- combining multiple sorted linked lists into one sorted list
Goal:
- efficiently merge all list while maintaining order
Example:
List 1:1 → 4 → 5
List 2:
1 → 3 → 4
List 3:
2 → 6
Output: 1 → 1 → 2 → 3 → 4 → 4 → 5 → 6
Explanation:
Smallest node is always selected first using Min Heap. This problem is one of the most important applications of:
Priority Queue (Min Heap) Constraints
0 <= K <= 10^40 <= Total Nodes <= 10^5Approach : Min Heap
Explanations:
Explanation:
The idea is:
- store first node of every list inside Min Heap
- always pick smallest node
- push next node from same list
Steps:
- Insert heads of all lists.
- Create Min Heap.
- Remove smallest node.
- Add node to answer list.
- Insert next node.
- Continue until heap becomes empty.
Observation:
Heap always contains smallest available node from each list.This approach:
- avoids repeated scanning
- efficiently merges
all sorted lists
Dry Run
Lists:1→4→5
1→3→4
2→6
Heap:
1,1,2
Remove: 1
Insert: 4
Heap:
1,2,4
Remove: 1
Insert: 3
Heap: 2,3,4
Continue...
Answer: 1→1→2→3→4→4→5→6
Practice :