Data Structures & AlgorithmsVery hardProduct company OA

Fenwick (binary indexed) tree, 1-based, built by point additions; then a[3] += 10. What is printed (the internal array, a range sum and a prefix sum)?

Fenwick (binary indexed) tree, 1-based, built by point additions; then a[3] += 10. What is printed (the internal array, a range sum and a prefix sum)?
n = 8
bit = [0] * (n + 1)
def add(i, d):
    while i <= n: bit[i] += d; i += i & -i
def pref(i):
    s = 0
    while i: s += bit[i]; i -= i & -i
    return s
for i, v in enumerate([3, 1, 4, 1, 5, 9, 2, 6], 1): add(i, v)
add(3, 10)
print(bit[1:], pref(6) - pref(2), pref(7))
  1. A. [3, 4, 14, 19, 5, 14, 2, 31] 29 35
  2. B. [3, 1, 14, 1, 5, 9, 2, 6] 29 35
  3. C. [3, 4, 14, 19, 5, 14, 2, 41] 19 25
  4. D. [3, 4, 14, 19, 5, 14, 2, 41] 29 35

Correct answer: D. [3, 4, 14, 19, 5, 14, 2, 41] 29 35

bit[i] stores the sum of a over (i − lowbit(i), i]: bit[2] = a1+a2 = 4, bit[4] = a1..a4, bit[6] = a5+a6, bit[8] = everything. The update at 3 climbs 3 → 4 → 8, so bit[3], bit[4] and bit[8] all grow by 10 (41 total). sum(a3..a6) = pref(6) − pref(2) = 14 + 1 + 5 + 9 = 29 and pref(7) = 35. Forgetting to propagate to bit[8] gives 31; using pref(6) − pref(3) drops a3. Both operations are O(log n).

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic