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?- A. 3 1 3 3
- B. 4 1 3 4
- C. 3 1 3 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
- Problem: A segment tree stores range sums. How many nodes does the recursive query visit? python a = [1, 3, 5, 7, 9, 11, 13, 15] visits =…
- Problem: Count the board states reachable on a 2 × 2 sliding puzzle ('0' is the blank, which swaps with an adjacent tile), using BFS over…
- Problem: Find the earliest time when all employees are connected, given friendship logs (time, a, b) and n people. python def…
- Problem: Find a redundant edge that, when removed, leaves a tree (return the last such edge in input order). python def redundant(edges)…
- Problem: Return the alien-dictionary letter order from a sorted list of words (Kahn's algorithm, ties alphabetical). python import heapq…
- Problem: Count how many nodes are 'safe' (every path from them ends at a terminal node) in a directed graph. python def safe(g): color =…