The problem involves merging K
sorted linked lists into one sorted linked list. This is a classic problem that can be solved efficiently using the K-Way Merge Pattern with a min-heap.
The min-heap helps us efficiently track the smallest elements across all lists, ensuring the merged list is sorted.
class Solution {
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> minHeap = new PriorityQueue<>((a, b) -> a.val - b.val);
// Step 1: Add the head of each list to the heap
for (ListNode node : lists) {
if (node != null) {
minHeap.offer(node);
}
}
// Step 2: Extract the smallest element and add the next node from the same list
ListNode dummy = new ListNode(-1);
ListNode current = dummy;
while (!minHeap.isEmpty()) {
ListNode smallest = minHeap.poll();
current.next = smallest;
current = current.next;
if (smallest.next != null) {
minHeap.offer(smallest.next);
}
}
return dummy.next;
}
}
O(K log K)
โ Adding the head of each list to the heap.O(N log K)
โ Extracting and adding elements to the heap, where N
is the total number of nodes.O(N log K)
.Input: lists = [[1,4,5],[1,3,4],[2,6]]
Output: [1,1,2,3,4,4,5,6]
Explanation:
- Add the head of each list to the heap: [1, 1, 2].
- Extract the smallest (1) and add the next node from the same list.
- Repeat until all nodes are merged into the result list.