K-way Merge
Merge k sorted lists or search across sorted rows with a min-heap of the current heads — kth smallest in a matrix, smallest range.
You have k sorted sequences and need them in one sorted order, or need the kth smallest item across them. Keep a min-heap holding the current head of each sequence. Pop the smallest head, output it, and push the next element from the same sequence.
- Merge k sorted lists, arrays or files (external sorting).
- Kth smallest across several sorted lists, or in a row- and column-sorted matrix.
- Smallest range covering at least one element from each list.
- Pairs from two sorted arrays with the smallest sums.
Merge k sorted lists
ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> heap = new PriorityQueue<>((a, b) -> a.val - b.val);
for (ListNode l : lists) if (l != null) heap.offer(l);
ListNode dummy = new ListNode(0), tail = dummy;
while (!heap.isEmpty()) {
ListNode n = heap.poll();
tail = tail.next = n;
if (n.next != null) heap.offer(n.next); // advance that list
}
return dummy.next;
}import heapq
def merge_k_lists(lists):
heap = [(l.val, i, l) for i, l in enumerate(lists) if l] # i breaks ties
heapq.heapify(heap)
dummy = tail = ListNode(0)
while heap:
_, i, n = heapq.heappop(heap)
tail.next = tail = n
if n.next:
heapq.heappush(heap, (n.next.val, i, n.next))
return dummy.nextfunction mergeKLists(lists: (ListNode | null)[]): ListNode | null {
const heap = new Heap<ListNode>((a, b) => a.val - b.val);
for (const l of lists) if (l) heap.push(l);
const dummy = new ListNode(0);
let tail = dummy;
while (heap.size) {
const n = heap.pop()!;
tail = tail.next = n;
if (n.next) heap.push(n.next);
}
return dummy.next;
}Kth smallest in a sorted matrix
Each row is a sorted list. Push the first element of every row (or of the first k rows), then pop k − 1 times, pushing the next element in the same row each time. The next top is the answer. O(k log min(k, n)).
The binary search on value alternative is often better: guess mid and count the elements ≤ mid in O(n) by walking from the bottom-left corner. O(n log(max − min)).
Smallest range covering k lists
Keep one element from each list in a min-heap and track the current maximum. The range is [heap top, max]. Pop the min and push its successor (which may raise the max). Record the best range. Stop when any list runs out.
int[] smallestRange(List<List<Integer>> nums) {
PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> a[0] - b[0]); // {val, list, idx}
int max = Integer.MIN_VALUE;
for (int i = 0; i < nums.size(); i++) {
heap.offer(new int[]{nums.get(i).get(0), i, 0});
max = Math.max(max, nums.get(i).get(0));
}
int[] best = {heap.peek()[0], max};
while (true) {
int[] t = heap.poll();
if (max - t[0] < best[1] - best[0]) best = new int[]{t[0], max};
if (t[2] + 1 == nums.get(t[1]).size()) return best; // one list exhausted
int nx = nums.get(t[1]).get(t[2] + 1);
max = Math.max(max, nx);
heap.offer(new int[]{nx, t[1], t[2] + 1});
}
}def smallest_range(nums):
heap = [(row[0], i, 0) for i, row in enumerate(nums)]
heapq.heapify(heap)
hi = max(row[0] for row in nums)
best = (heap[0][0], hi)
while True:
lo, i, j = heapq.heappop(heap)
if hi - lo < best[1] - best[0]:
best = (lo, hi)
if j + 1 == len(nums[i]):
return list(best)
nx = nums[i][j + 1]
hi = max(hi, nx)
heapq.heappush(heap, (nx, i, j + 1))function smallestRange(nums: number[][]): number[] {
const heap = new Heap<[number, number, number]>((a, b) => a[0] - b[0]);
let hi = -Infinity;
nums.forEach((row, i) => { heap.push([row[0], i, 0]); hi = Math.max(hi, row[0]); });
let best = [heap.peek()![0], hi];
while (true) {
const [lo, i, j] = heap.pop()!;
if (hi - lo < best[1] - best[0]) best = [lo, hi];
if (j + 1 === nums[i].length) return best;
const nx = nums[i][j + 1];
hi = Math.max(hi, nx);
heap.push([nx, i, j + 1]);
}
}- Merge k Sorted Listshard
- Kth Smallest Element in a Sorted Matrixmedium
- Find K Pairs with Smallest Sumsmedium
- Smallest Range Covering Elements from K Listshard
- Merge Sorted Arrayk = 2, fill from the backeasy
- Ugly Number IImerge three generated sequencesmedium
- Heap of the k current heads; pop the min, push its successor.
- O(N log k) time, O(k) space.
- Track the max alongside the heap for range problems.
- Kth smallest can also be found by binary searching on the value.