What is a Fenwick tree (Binary Indexed Tree)?

Answer

A Fenwick Tree (Binary Indexed Tree, BIT) is a data structure that efficiently computes prefix sums and supports point updates. More memory-efficient and simpler to implement than a segment tree for sum queries. Key idea: uses the binary representation of indices to determine what range each node stores. bit[i] stores the sum of elements from index i - lowbit(i) + 1 to i, where lowbit(i) = i & (-i) (the lowest set bit). Operations: Update(i, delta): O(log n) — propagate from i upward: while i ≤ n: bit[i] += delta; i += lowbit(i); PrefixSum(i): O(log n) — sum from 1 to i: while i > 0: sum += bit[i]; i -= lowbit(i); Range sum(l, r): prefixSum(r) - prefixSum(l-1). Space: O(n). BIT is initialized to all zeros; add elements via updates. Applications: (1) Count inversions in an array; (2) Dynamic prefix sum; (3) Counting smaller elements to the right; (4) 2D BIT for 2D range sum queries. BIT vs Segment Tree: BIT is simpler (15 lines vs 50), uses less memory (O(n) vs O(4n)), but only handles sum queries; Segment Tree handles sum, min, max, GCD, and more.