K-Way Merge Pattern
The k-way merge pattern is a technique used to merge k
sorted arrays (or linked lists) into a single sorted array. It's commonly used in problems like merging multiple sorted arrays, finding the smallest range covering elements from k
lists, and more.
Problem Statement
Given k
sorted arrays, merge them into one sorted array.
Approach
- Min-Heap: We use a min-heap (or priority queue) to efficiently fetch the smallest element among the
k
arrays. - Initialization: Insert the first element of each array into the heap.
- Merging: Repeatedly extract the smallest element from the heap and add the next element from the same array to the heap until all elements are merged.
Example
Let's consider an example with k = 3
arrays:
const arrays = [
[1, 4, 5],
[1, 3, 4],
[2, 6]
];
We want to merge these arrays into a single sorted array.
Steps
- Insert First Elements: Start by inserting the first element from each array into the heap:
- Heap:
[1, 1, 2]
- Heap:
- Extract Min: Extract
1
(smallest element) from the heap and insert the next element from the same array:- Heap:
[1, 2, 4]
- Heap:
- Repeat: Continue this process until all elements are merged.
Code Implementation
Here’s a sample implementation in JavaScript:
function mergeKSortedArrays(arrays) {
const minHeap = new MinHeap();
const result = [];
// Initialize the heap with the first element of each array
for (let i = 0; i < arrays.length; i++) {
if (arrays[i].length > 0) {
minHeap.enequeue(arrays[i][0], i, 0);
}
}
while (minHeap.heap.length > 0) {
const { val, arrIndex, valIndex } = minHeap.dequeue();
result.push(val);
// If the array has more elements, add the next element to the heap
if (valIndex + 1 < arrays[arrIndex].length) {
minHeap.enequeue(arrays[arrIndex][valIndex + 1], arrIndex, valIndex + 1);
}
}
return result;
}
// Example usage
const arrays = [
[1, 4, 5],
[1, 3, 4],
[2, 6]
];
const result = mergeKSortedArrays(arrays);
console.log(result); // Output: [1, 1, 2, 3, 4, 4, 5, 6]
Complexity Analysis
- Time Complexity: O(N log k), where
N
is the total number of elements across all arrays andk
is the number of arrays. - Space Complexity: O(k) for storing elements in the heap.
Use Cases
- Merging multiple log files.
- Finding the smallest range covering elements from
k
sorted lists. - K-way merge in external sorting.
Conclusion
The k-way merge pattern is a powerful technique for efficiently merging multiple sorted arrays. It leverages a min-heap to always extract the smallest element, ensuring that the resulting array is sorted.