Fenwick tree (binary indexed tree)
In short: A Fenwick tree stores an array of numbers so that both updating a value and computing prefix sums take O(log n).
In more detail: It is a particularly compact alternative to the segment tree when only sums (or similar invertible operations) are needed. The tree lives in a plain array, and the index arithmetic uses the lowest set bit.
In Depth
- Idea: Position
istores the sum of a section whose length equals the largest power of two dividingi. - Query: Prefix sum up to
i: add the value, theni -= i & -iuntiliis 0. - Update: Change a value by
d: add ati, theni += i & -iuntiliexceeds the size. - Range sum:
sum(r) - sum(l-1). - Build: Possible in O(n), memory only n numbers.
- Limits: Not every operation is invertible. A range minimum therefore usually needs the segment tree.
See also: Big-O notation