FAANGPrep Sprint
Merge K Sorted Lists
Merge k sorted linked lists into one sorted linked list.
Problem Understanding
lists holds k linked lists, each already sorted in ascending order.
Combine them into a single linked list that is also sorted in ascending order, and return its head.
Example:
- Input:
lists = [[1,4,5],[1,3,4],[2,6]] - Output:
[1,1,2,3,4,4,5,6]
Algorithm Strategy
Min-Heap Approach (O(N log k))
Instead of comparing the heads of all k lists at every step (which takes O(k)), we can use a Min-Heap.
- Initialize: Push the head node of every non-empty list into a Min-Heap.
- Iterate: While heap is not empty:
- Pop the smallest node (root) from heap.
- Add this node to our result list.
- If the popped node has a
nextnode, push thatnextnode into the heap.
- Result: The result list is sorted.
Interactive Visualization
k = 3 · AT MOST ONE NODE PER LIST IN THE HEAP
PUSH HEAD
lists
L1
1
→
4
→
5
→ NULL
L2
1
→
3
→
4
→ NULL
L3
2
→
6
→ NULL
result
not started
Heap
1/3
Linked
0/8
Push the head of list 1: 1
Next
Push the head of list 2: 1
Lists
The k lists as chains, the min-heap holding the front node of each, and the result growing from a dummy node. Each pop links the smallest node into the result and pushes the node after it.
