Data Structures & AlgorithmsVery hardProduct company OA

Problem: Find the smallest range [lo, hi] that contains at least one number from each of k sorted lists (min-heap of one pointer per list, tracking the current maximum).

Problem: Find the smallest range [lo, hi] that contains at least one number from each of k sorted lists (min-heap of one pointer per list, tracking the current maximum).
import heapq
def smallest_range(lists):
    h = [(l[0], i, 0) for i, l in enumerate(lists)]; heapq.heapify(h)
    hi = max(l[0] for l in lists); best = (h[0][0], hi)
    while True:
        lo, i, j = heapq.heappop(h)
        if hi - lo < best[1] - best[0]: best = (lo, hi)
        if j + 1 == len(lists[i]): return best
        nxt = lists[i][j + 1]; hi = max(hi, nxt)
        heapq.heappush(h, (nxt, i, j + 1))
print(smallest_range([[3, 9, 15, 30], [1, 10, 21], [7, 12, 16, 22]]))
What is printed?
  1. A. (1, 7)
  2. B. (9, 12)
  3. C. (7, 10)
  4. D. (10, 12)

Correct answer: C. (7, 10)

The heap holds one current element per list; the window is [heap minimum, running maximum]. Advancing the list that owns the minimum is the only move that can shrink the window. Windows seen: (1, 7) width 6, (3, 10) width 7, (7, 10) width 3, (9, 12) width 3 (not smaller), … Stop when a list is exhausted. (7, 10) holds 9, 10 and 7. O(N log k) for N total elements.

More Coding Interview Problems questions

Exams that ask this topic