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

Problem: n, q ≤ 2·10⁵ operations of two kinds: add v to every a[l..r], and ask for sum a[l..r]. A Fenwick tree with two arrays supports both in O(log n): prefix(i) = sum1(i)·i − sum2(i).

Problem: n, q ≤ 2·10⁵ operations of two kinds: add v to every a[l..r], and ask for sum a[l..r]. A Fenwick tree with two arrays supports both in O(log n): prefix(i) = sum1(i)·i − sum2(i).
class RangeBIT:
    def __init__(s, n): s.n = n; s.b1 = [0] * (n + 1); s.b2 = [0] * (n + 1)
    def _add(s, b, i, v):
        while i <= s.n: b[i] += v; i += i & -i
    def _sum(s, b, i):
        r = 0
        while i > 0: r += b[i]; i -= i & -i
        return r
    def add(s, l, r, v):
        s._add(s.b1, l, v); s._add(s.b1, r + 1, -v)
        s._add(s.b2, l, v * (l - 1)); s._add(s.b2, r + 1, -v * r)
    def prefix(s, i): return s._sum(s.b1, i) * i - s._sum(s.b2, i)
    def query(s, l, r): return s.prefix(r) - s.prefix(l - 1)
t = RangeBIT(8)
t.add(2, 5, 3); t.add(4, 8, 2); t.add(1, 1, 7)
print(t.query(1, 8), t.query(3, 4), t.query(6, 6))
What is printed?
  1. A. 29 8 5
  2. B. 29 5 2
  3. C. 27 8 2
  4. D. 29 8 2

Correct answer: D. 29 8 2

b1 is a difference array of the values; b2 corrects the prefix formula so that prefix(i) = Σ_{j≤i} a[j]. After the updates the array (1-based) is 7, 3, 3, 5, 5, 2, 2, 2 → total 29, a[3] + a[4] = 3 + 5 = 8, a[6] = 2 (a naive simulation agrees). A plain prefix-sum array needs O(n) per update and a plain Fenwick tree handles only point updates; a lazy segment tree is the other O(log n) option.

More Coding Interview Problems questions

Exams that ask this topic