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

Problem: A segment tree stores range sums. How many nodes does the recursive query visit?

Problem: A segment tree stores range sums. How many nodes does the recursive query visit?
a = [1, 3, 5, 7, 9, 11, 13, 15]
visits = 0
def build(node, l, r, t):
    if l == r: t[node] = a[l]; return
    m = (l + r) // 2
    build(2*node, l, m, t); build(2*node+1, m+1, r, t)
    t[node] = t[2*node] + t[2*node+1]
def query(node, l, r, ql, qr, t):
    global visits; visits += 1
    if qr < l or r < ql: return 0
    if ql <= l and r <= qr: return t[node]
    m = (l + r) // 2
    return query(2*node, l, m, ql, qr, t) + query(2*node+1, m+1, r, ql, qr, t)
t = [0] * 16; build(1, 0, 7, t)
print(query(1, 0, 7, 2, 6, t), visits)
What is printed?
  1. A. 45 15
  2. B. 45 9
  3. C. 40 9
  4. D. 45 7

Correct answer: B. 45 9

Sum of a[2..6] = 5 + 7 + 9 + 11 + 13 = 45. The query stops at nodes fully inside [2, 6] ([2,3], [4,5], [6,6]) or fully outside, so only O(log n) nodes are visited – here 9 out of 15. A naive loop would touch 5 elements but O(n) in general.

More Coding Interview Problems questions

Exams that ask this topic