Data Structures & AlgorithmsVery hardGoogle · Flipkart interview

Problem: A Fenwick tree over a DIFFERENCE array supports 'add v to a[l..r]' and 'read a[i]' in O(log n) (1-indexed, all zeros initially).

Problem: A Fenwick tree over a DIFFERENCE array supports 'add v to a[l..r]' and 'read a[i]' in O(log n) (1-indexed, all zeros initially).
n = 8; bit = [0] * (n + 2)
def upd(i, v):
    while i <= n: bit[i] += v; i += i & -i
def range_add(l, r, v): upd(l, v); upd(r + 1, -v)
def point(i):
    s = 0
    while i > 0: s += bit[i]; i -= i & -i
    return s
range_add(2, 6, 5); range_add(4, 8, 3); range_add(1, 3, -2)
print(point(3), point(5), point(8))
What is printed?
  1. A. 5 8 3
  2. B. 3 5 3
  3. C. 3 8 0
  4. D. 3 8 3

Correct answer: D. 3 8 3

A prefix sum of the difference array is the element value: a[3] = 5 − 2 = 3, a[5] = 5 + 3 = 8, a[8] = 3. upd(r + 1, −v) cancels the addition after r (for r = 8 it falls outside the array and is skipped).

More Coding Interview Problems questions

Exams that ask this topic