What are Fenwick Trees (Binary Indexed Trees), and how do they work?

Instruction: Explain the concept of Fenwick Trees and their application in computational algorithms.

Context: This question is designed to assess the candidate's understanding of Fenwick Trees, a data structure that provides efficient methods for calculation and manipulation of the prefix sums of a table of values.

Updated

Official answer

A Fenwick tree stores partial sums in an array. With one-based indexing, entry i summarizes the interval [i-lowbit(i)+1, i], where lowbit(i)=i & -i. Prefix queries subtract lowbit; point increments add it.

class Fenwick:
    def __init__(self, n):
        if not isinstance(n, int) or n < 0:
            raise ValueError('n must be a nonnegative integer')
        self.n = n
        self.tree = [0] * (n + 1)

    def add(self, i, delta):
        if not isinstance(i, int) or not 1 <= i <= self.n:
            raise IndexError('update index out of range')
        while i <= self.n:
            self.tree[i] += delta
            i += i & -i

    def prefix(self, i):
        if not isinstance(i, int) or not 0 <= i <= self.n:
            raise IndexError('prefix index out of range')
        total = 0
        while i:
            total += self.tree[i]
            i -= i & -i
        return total

The prefix includes indices 1 through i; prefix(0)=0. For 1≤l≤r≤n, range sum is prefix(r)-prefix(l-1). add increments a value; assigning a new value requires the difference from the old value. Reject update index zero, which otherwise would not advance.

Operations take O(log n) under constant-cost arithmetic and storage is O(n). Building by n calls to add costs O(n log n); a linear construction is also possible. Frequency/order-statistic uses require additional assumptions such as nonnegative frequencies and a mapped ordered key domain. Ordinary investment returns do not become additive merely because prefix sums are available.

Related Questions