Data Structures19 sections · 729 units
Open in Course

K-Way Merge with Heap

The algorithm

1.1. Initialize a min-heap with the first element from each list (along with list index and position).

2.2. Extract the minimum. The extracted value is the next element in the merged output.

3.3. If that list has more elements, insert the next one into the heap.

4.4. Repeat until heap is empty. The heap always has at most kk elements. Each of the nn total elements is inserted and extracted once. Total: O(nlogk)O(n \log k).