Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Range minimum queries with a sparse table after O(n log n) preprocessing.

Problem: Range minimum queries with a sparse table after O(n log n) preprocessing.
a = [7, 2, 9, 4, 3, 8, 6, 1, 5]
n = len(a); LOG = n.bit_length()
sp = [a[:]]
for k in range(1, LOG):
    prev = sp[-1]
    sp.append([min(prev[i], prev[i + (1 << (k - 1))]) for i in range(n - (1 << k) + 1)])
def rmq(l, r):
    k = (r - l + 1).bit_length() - 1
    return min(sp[k][l], sp[k][r - (1 << k) + 1])
print(rmq(2, 5), rmq(0, 8), rmq(4, 4), len(sp))
What is printed?
  1. A. 3 1 3 3
  2. B. 4 1 3 4
  3. C. 3 1 3 4
  4. D. 3 2 3 4

Correct answer: C. 3 1 3 4

sp[k][i] is the minimum of a[i .. i + 2ᵏ − 1]. A query covers [l, r] with two overlapping blocks of size 2ᵏ, which is fine because min is idempotent: O(1) per query. a[2..5] = 9, 4, 3, 8 → 3. n = 9 has bit length 4, so levels k = 0..3. Static data only – updates need a segment tree.

More Coding Interview Problems questions

Exams that ask this topic