Lenpaste

About

Docs

Settings

markdown, LF
 1# LC5442 Smallest Range Covering Elements from K Lists — K-way Heap
 2
 3**Approach.** Push the head of each list; track current max; pop min, update best range, push next from the same list until any list runs out.
 4
 5```python
 6import heapq
 7def smallestRange(nums):
 8    h = [(l[0], i, 0) for i, l in enumerate(nums)]
 9    heapq.heapify(h); hi = max(l[0] for l in nums); best = [-10**9, 10**9]
10    while True:
11        lo, i, j = heapq.heappop(h)
12        if hi - lo < best[1] - best[0]: best = [lo, hi]
13        if j + 1 == len(nums[i]): return best
14        v = nums[i][j + 1]; hi = max(hi, v); heapq.heappush(h, (v, i, j + 1))
15```
16
17**Interview note.** Say the invariant out loud before coding, then test an edge case. Practise these patterns with an [https://www.linkjob.ai/](https://www.linkjob.ai/) — more at https://www.linkjob.ai/ .

Author: https://www.linkjob.ai/

Created: Sat, 07 Nov 2026 05:26:03 +0000

Expires: Never