The K-Way Merge pattern helps efficiently merge K
sorted lists (arrays or linked lists)
into one sorted list. This generalizes the traditional 2-way merge (like in merge sort).
One popular approach uses a min-heap (priority queue):
Use Case: Merging K sorted streams/logs, external sorting, median computation, etc.
class Solution {
public List<Integer> mergeKSortedLists(List<List<Integer>> lists) {
PriorityQueue<int[]> minHeap = new PriorityQueue<>((a, b) -> a[0] - b[0]);
List<Integer> result = new ArrayList<>();
// Step 1: Add the first element of each list to the heap
for (int i = 0; i < lists.size(); i++) {
if (!lists.get(i).isEmpty()) {
minHeap.offer(new int[]{lists.get(i).get(0), i, 0}); // [value, listIndex, elementIndex]
}
}
// Step 2: Extract the smallest element and add the next element from the same list
while (!minHeap.isEmpty()) {
int[] smallest = minHeap.poll();
result.add(smallest[0]);
int listIndex = smallest[1];
int elementIndex = smallest[2];
// Add the next element from the same list to the heap
if (elementIndex + 1 < lists.get(listIndex).size()) {
minHeap.offer(new int[]{lists.get(listIndex).get(elementIndex + 1), listIndex, elementIndex + 1});
}
}
return result;
}
}
O(K log K)
โ Adding the first element of each list to the heap.O(N log K)
โ Extracting and adding elements to the heap, where N
is the total number of elements across all lists.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 first element of each list to the heap: [1, 1, 2].
- Extract the smallest (1) and add the next element from the same list.
- Repeat until all elements are merged into the result list.