Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Point-update / range-maximum segment tree (iterative, size n = 8).
Problem: Point-update / range-maximum segment tree (iterative, size n = 8).
n = 8; t = [0] * (2 * n)
def upd(i, v):
i += n; t[i] = v
while i > 1: i //= 2; t[i] = max(t[2*i], t[2*i+1])
def qry(l, r): # inclusive l..r
res = float('-inf'); l += n; r += n + 1
while l < r:
if l & 1: res = max(res, t[l]); l += 1
if r & 1: r -= 1; res = max(res, t[r])
l //= 2; r //= 2
return res
for i, v in enumerate([4, 9, 2, 7, 5, 1, 8, 3]): upd(i, v)
upd(1, 0); upd(5, 6)
print(qry(0, 3), qry(2, 6), qry(4, 5))What is printed?- A. 9 8 6
- B. 7 7 6
- C. 7 8 5
- D. 7 8 6
Correct answer: D. 7 8 6
After the updates the array is [4, 0, 2, 7, 5, 6, 8, 3]. Max of 0..3 = 7, of 2..6 = 8, of 4..5 = 6. The half-open bottom-up loop handles odd boundaries by taking the lone node and moving inward.
More Coding Interview Problems questions
- Mo's algorithm answers q offline range queries on an array of n elements by sorting queries into √n-sized blocks of their left ends. If…
- Problem: Edges arrive one by one; report the first edge that creates an ODD cycle (making the graph non-bipartite), using union-find with…
- Problem: Total weight of a MAXIMUM spanning tree (Kruskal with edges sorted in decreasing order). python edges =…
- Find the bug: Dijkstra (finalising a node when first popped) is run on a graph with a NEGATIVE edge. Compare with Bellman–Ford. python…
- Problem: Topological order produced by DFS (append a node after all its descendants, then reverse). python g = {0: [2, 1], 1: [3], 2: [3…
- Problem: Maximum bipartite matching between workers (left) and jobs (right) with Kuhn's augmenting-path algorithm. python adj = {0: [0…