#23
Merge k Sorted Lists
HardLinked ListDivide and ConquerHeap (Priority Queue)Merge SortHeapLinked ListDivide and Conquer
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution (Heap)★ | |
|---|---|---|
| Time | O(n²) | O(n log k) |
| Space | O(1) | O(k) |
💡
Intuition
Time O(n log k)Space O(k)
Using a min-heap (or priority queue) allows us to efficiently merge the k sorted lists by always extracting the smallest element. This approach is much faster than the brute force method.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a min-heap and add the head of each linked list to it.
- 2Step 2: While the heap is not empty, extract the smallest element, add it to the merged list, and if the extracted element has a next node, add that next node to the heap.
- 3Step 3: Continue until all elements from all lists have been processed.
solution.py24 lines
1# Full working Python code with comments
2import heapq
3
4class ListNode:
5 def __init__(self, val=0, next=None):
6 self.val = val
7 self.next = next
8
9def mergeKLists(lists):
10 min_heap = []
11 # Step 1: Initialize the heap
12 for l in lists:
13 if l:
14 heapq.heappush(min_heap, (l.val, l))
15 dummy = ListNode(0)
16 current = dummy
17 # Step 2: Process the heap
18 while min_heap:
19 val, node = heapq.heappop(min_heap)
20 current.next = ListNode(val)
21 current = current.next
22 if node.next:
23 heapq.heappush(min_heap, (node.next.val, node.next))
24 return dummy.nextℹ
Complexity note: The time complexity is O(n log k) because we are processing n elements and for each insertion and extraction from the heap, it takes log k time. The space complexity is O(k) due to the storage of the heap containing at most k elements.
- 1Using a min-heap allows us to efficiently merge multiple sorted lists by always extracting the smallest element, which is a common pattern in problems involving merging sorted data.
- 2Understanding the trade-offs between time and space complexity is crucial; sometimes a more efficient time complexity can be achieved at the cost of increased space usage.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.