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))- A. [3, 4, 14, 19, 5, 14, 2, 31] 29 35
- B. [3, 1, 14, 1, 5, 9, 2, 6] 29 35
- C. [3, 4, 14, 19, 5, 14, 2, 41] 19 25
- 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).
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- Segment tree for range-minimum with lazy range-add (the pending add stays at a node and is applied on the way up instead of being pushed…
- Four cities, symmetric distances; the bitmask DP (Held–Karp) is compared with the nearest-neighbour heuristic, both starting and ending at…
- Maximum-weight independent set on a tree (no two chosen nodes adjacent) by tree DP returning (best if u taken, best if u skipped)…
- BFS that also counts the number of shortest paths. What is printed (dist[7], ways[7], ways[6], ways[4])? python from collections import…
- Dijkstra with a binary heap and lazy deletion (no decrease-key; outdated entries are skipped when popped). What is printed (dist to E…
- AVL insertions (rotations labelled by imbalance case). What is printed (preorder, rotation cases in order, height in edges)? python class…