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?- A. (1, 7)
- B. (9, 12)
- C. (7, 10)
- 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
- Problem: Choose the root(s) that minimise the height of an unrooted tree. Repeatedly strip all current leaves; the last 1 or 2 nodes are…
- Problem: Count the strongly connected components of a directed graph with Kosaraju's algorithm (DFS finishing order, then DFS on the…
- Problem: Stones sit on grid points; a stone may be removed if another remaining stone shares its row or column. Maximum removable = stones…
- Problem: Build row k of Pascal's triangle (row 0 = [1]) by adding neighbouring entries of the previous row. python def pascalrow(k): row =…
- Problem: Count binary strings of length n with no two adjacent 1s, tracking how many valid strings end in 0 and in 1. python def no11(n)…
- Problem: Find the minimum sum of a falling path through a square grid: start anywhere in the top row and move to one of the (up to) three…