# LC5442 Smallest Range Covering Elements from K Lists — K-way Heap

**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.

```python
import heapq
def smallestRange(nums):
    h = [(l[0], i, 0) for i, l in enumerate(nums)]
    heapq.heapify(h); hi = max(l[0] for l in nums); best = [-10**9, 10**9]
    while True:
        lo, i, j = heapq.heappop(h)
        if hi - lo < best[1] - best[0]: best = [lo, hi]
        if j + 1 == len(nums[i]): return best
        v = nums[i][j + 1]; hi = max(hi, v); heapq.heappush(h, (v, i, j + 1))
```

**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/ .
