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

Problem: Maintain prefix sums under point updates with a Fenwick tree (1-indexed).

Problem: Maintain prefix sums under point updates with a Fenwick tree (1-indexed).
int n = 8; vector<long long> t(n + 1, 0);
void add(int i, long long v) { for (; i <= n; i += i & -i) t[i] += v; }
long long pre(int i) { long long s = 0; for (; i > 0; i -= i & -i) s += t[i]; return s; }
// values 5, 2, 9, -3, 4, 1, 7, 6 added at positions 1..8, then add(4, 10)
// cout << pre(4) << " " << pre(7) - pre(2) << " " << t[8];
What is printed?
  1. A. 13 28 41
  2. B. 23 28 41
  3. C. 23 18 41
  4. D. 23 28 31

Correct answer: B. 23 28 41

i & −i is the lowest set bit, which gives each node's range length. After adding 10 at position 4 the array is 5, 2, 9, 7, 4, 1, 7, 6: prefix(4) = 23, positions 3..7 sum to 28, and t[8] covers all 8 positions = 41. Both operations are O(log n).

More Coding Interview Problems questions

Exams that ask this topic