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?
  1. A. 9 8 6
  2. B. 7 7 6
  3. C. 7 8 5
  4. 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

Exams that ask this topic