Skip to content
StackDecode
Advanced data structuresAnimated

Fenwick Tree (Binary Indexed Tree)

Prefix sums using clever binary-indexed partial sums.

Time

O(log n)

Extra space

O(n)

Use it for

Compact prefix-sum with updates.

How it works

  1. A Fenwick tree (binary indexed tree) answers "sum of the first k items" and supports updates, each in O(log n), using one array.
  2. Slot i (counting from 1) stores the sum of the last lowbit(i) items ending at i. lowbit(i) is the value of the lowest 1-bit of i: 6 = 110₂ has lowbit 2, so slot 6 holds a[5] + a[6].
  3. Build: add each item into its slot, then pass the slot up to its parent i + lowbit(i).
  4. Query: add slot k, then jump to k − lowbit(k), and repeat until you reach 0. At most log₂ n slots are visited.

Watch it run

Loading animation…