Watch how a min-heap efficiently merges K sorted linked lists by always extracting the smallest element.
Heap / Priority Queue LeetCode 23 ↗ Hardk linked lists lists, each linked list is sorted in ascending order.lists = [[1,4,5],[1,3,4],[2,6]], the merged result is [1,1,2,3,4,4,5,6].
import java.util.PriorityQueuefun mergeKLists(lists: List<List<Int>>): List<Int> { val heap = PriorityQueue<Triple<Int, Int, Int>>(compareBy { it.first }) for ((i, lst) in lists.withIndex()) { if (lst.isNotEmpty()) { heap.add(Triple(lst[0], i, 0)) } } val result = mutableListOf<Int>() while (heap.isNotEmpty()) { val (value, listIdx, elemIdx) = heap.poll() result.add(value) if (elemIdx + 1 < lists[listIdx].size) { val nextVal = lists[listIdx][elemIdx + 1] heap.add(Triple(nextVal, listIdx, elemIdx + 1)) } } return result}
We need to merge k sorted lists into a single sorted list. At every step, the next element
in the merged result must be the smallest among all current heads of the k lists.
A min-heap (priority queue) lets us find that minimum in O(log k) time instead of
scanning all k heads in O(k).
Without a heap, finding the minimum across k list heads takes O(k) per extraction, leading to O(N × k) total time. The heap reduces each extraction to O(log k), giving O(N log k) total — a significant improvement when k is large.
Where N is the total number of elements across all lists, and k is the
number of lists. Each of the N elements is pushed and popped from the heap exactly once, and each
heap operation costs O(log k). The heap holds at most k elements at any time.