Merge K Sorted Lists
Master this topic with zero to advance depth.
Merge K Sorted Lists
You are given an array of k linked-lists lists, each linked-list is sorted in ascending order.
Merge all the linked-lists into one sorted linked-list and return it.
Visual Representation
lists = [
1->4->5,
1->3->4,
2->6
]
Min-Heap State:
1. Insert heads: [1, 1, 2]
2. Extract 1, add next(4): Heap = [1, 2, 4]
3. Extract 1, add next(3): Heap = [2, 3, 4]
4. Extract 2, add next(6): Heap = [3, 4, 6]...
Merged Result:
1->1->2->3->4->4->5->6Examples
Level I: Brute Force (Array + Sort)
Intuition
The simplest approach is to ignore the linked list structure initially. We can traverse all the linked lists, collect all the values into an array, sort the array, and then build a new linked list from the sorted array.
Detailed Dry Run
lists = [[1,4,5],[1,3,4],[2,6]]
- Collect: [1,4,5,1,3,4,2,6]
- Sort: [1,1,2,3,4,4,5,6]
- Build new list: 1->1->2->3->4->4->5->6
⚠️ Common Pitfalls & Tips
O(N log N) time and O(N) space. Not optimal for large lists.
Visual Trace
Lists: [1->4, 1->3]
1. Array: [1, 4, 1, 3]
2. Sorted: [1, 1, 3, 4]
3. Linked: 1 -> 1 -> 3 -> 4Level II: Divide and Conquer
Intuition
Merge lists in pairs, decreasing the number of lists by half in each step. This is more efficient than merging one by one and avoids the overhead of a Min-Heap if k is small.
Visual Trace
[L1, L2, L3, L4]
\ / \ /
[L12] [L34]
\ /
[Final]Detailed Dry Run
Lists = [L1, L2, L3, L4]. 1. Merge(L1, L2)=L12, Merge(L3, L4)=L34. 2. Merge(L12, L34) = Result.
⚠️ Common Pitfalls & Tips
Deep recursion could cause stack overflow in some environments, though log(k) is usually safe.
Level III: Min-Heap (Optimal)
Intuition
Use a Min-Heap (Priority Queue) to always extract the smallest current node among the heads of all k lists.
Detailed Dry Run
lists = [[1,4,5], [1,3,4], [2,6]]
- Heap: [(1: from L1), (1: from L2), (2: from L3)]
- Pop 1 (L1). Res: [1]. Push 4 (L1). Heap: [1, 2, 4]
- Pop 1 (L2). Res: [1,1]. Push 3 (L2). Heap: [2, 3, 4]...
⚠️ Common Pitfalls & Tips
In Python, using a tie-breaker like i or a wrapper is necessary for heapq when values are equal.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.