Skip to content
Visual explainer 3h to learn 4 steps

Fenwick tree (binary indexed tree)

Implement a Fenwick tree for prefix sums with point updates in O(log n).

By Invicly Tech, , in Data Structures & Algorithms. About 13 minutes to read.

Topic 50 of 54

In short

A Fenwick tree, or binary indexed tree, stores partial sums in a plain array so both prefix-sum queries and point updates cost O(log n). Each index is responsible for a range whose length is its lowest set bit. It is shorter to code than a segment tree when you only need sums.

Explained simply

Imagine one million player scores that change all the time, and you often ask: what is the total of players 1 to 5000? Adding them up each time is slow. A prefix sum array answers fast, but every score change forces you to rewrite many entries. A Fenwick tree does both jobs in about 20 steps for a million items, because log2 of one million is about 20.

The idea: each box in a helper array stores the total of a small block of the original array that ends at that box. The block sizes are powers of two (1, 2, 4, 8 and so on), and the binary form of the box number decides the size.

To get a prefix total, you add up a few boxes, jumping backward each time. To change one element, you update the few boxes whose blocks contain it, jumping forward each time. Both jumps use one small bit trick.

It is also called a binary indexed tree (BIT). Peter Fenwick described it in 1994. It is tiny: an array of n + 1 numbers and two loops of three lines each, which makes it a favourite in contests and interviews.

Press Play on a diagram to walk through it one step at a time.

CompareRange sums on a changing array
Plain array
  • Update O(1)
  • Range sum O(n)
  • No extra memory
Prefix sum array
  • Update O(n)
  • Range sum O(1)
  • Best for static data
Fenwick tree
  • Update O(log n)
  • Range sum O(log n)
  • O(n) memory
CompareFenwick tree or segment tree?
Fenwick tree
  • n + 1 cells
  • Sum, xor and counts (invertible ops)
  • About 10 lines of code
  • Small constant factor, fast in practice
Segment tree
  • About 4n cells recursive, 2n iterative
  • Any associative op: min, max, gcd
  • Range updates with lazy propagation
  • More code, more ways to slip

In depth

What each cell really stores

Use 1-based indexes. lowbit(i) is the value of the lowest set bit of i, computed as i & -i. In two's complement, -i flips every bit of i and adds 1, so only the lowest 1 bit survives the AND. Python integers behave like infinite two's complement for &, so the trick works there too.

Cell t[i] stores the sum of a[i - lowbit(i) + 1] through a[i], a block of length lowbit(i) that ends at i. So t[6] (binary 110, lowbit 2) holds a[5] + a[6]. t[8] (1000, lowbit 8) holds a[1] through a[8]. Every odd index has lowbit 1 and holds just one element.

These blocks nest neatly: each block is either inside another or does not touch it. That nesting forms a tree, which is where the name comes from, even though it is stored as a flat array.

MapWhich elements each cell covers (n = 8)
t[8] covers a[1..8]
  • t[4] covers a[1..4]
    • t[2] covers a[1..2]
    • t[1] covers a[1]
    • t[3] covers a[3]
  • t[6] covers a[5..6]
    • t[5] covers a[5]
  • t[7] covers a[7]

Why both walks take O(log n)

The query walk does i -= i & -i, which clears the lowest set bit of i. A number up to n has at most floor(log2 n) + 1 set bits, so the walk takes at most that many steps. prefix(13) reads t[13], t[12] and t[8], then stops at 0: three cells for 13 = 1101 in binary, one per set bit.

The update walk does i += i & -i. Adding the lowest set bit causes a carry, so the lowest set bit of the new i is in a strictly higher position. Positions only go up and stop once i passes n, so this walk also takes at most about log2 n + 1 steps. Updating a[5] in a tree of size 16 touches t[5], t[6], t[8] and t[16]: exactly the blocks that contain position 5.

For n = 10^6, that is at most 20 steps either way.

Flowprefix(13) walks down by clearing bits
  1. Step 1
    i = 13 (1101)

    Add t[13], covers a[13].

  2. Step 2
    i = 12 (1100)

    Add t[12], covers a[9..12].

  3. Step 3
    i = 8 (1000)

    Add t[8], covers a[1..8].

  4. Step 4
    i = 0

    Stop: total is a[1..13].

Building in O(n) and setting values

The simple build calls add(i, a[i]) for every i, which is O(n log n). There is a linear build: copy the array into t with a 0 in front, then for i from 1 to n, let j = i + (i & -i), and if j is at most n do t[j] += t[i]. Each cell pushes its finished total into its parent once, so the build is O(n).

A Fenwick tree only knows how to add a delta. To set a[i] to a new value v, you must add v - a[i], which means you keep a plain copy of the array next to the tree. Forgetting this and calling add(i, v) is a very common bug: the element ends up as old plus new.

There is also a 0-based variant: query uses r = (r & (r + 1)) - 1, update uses i = i | (i + 1). Both are correct; pick one and stay with it.

Range updates and other variations

Flip the roles to get range update with point query. Build the tree over a difference array: to add d to every element from l to r, call add(l, d) and add(r + 1, -d). Then prefix(i) is the current value of a[i]. Both operations are O(log n).

If you need range update and range sum at the same time, use two Fenwick trees. With B1 and B2, a range add of d on [l, r] does B1.add(l, d), B1.add(r + 1, -d), B2.add(l, d * (l - 1)) and B2.add(r + 1, -d * r). Then prefix(i) = B1.prefix(i) * i - B2.prefix(i).

The structure also extends to two dimensions: a grid of n by m with point updates and rectangle sums, each costing O(log n * log m).

  • Range add, point query: tree over the difference array
  • Range add, range sum: two trees
  • 2D Fenwick: O(log n * log m) per operation

Counting with a Fenwick tree, and its limits

A Fenwick tree over value ranks works as a dynamic counter. To count inversions, scan left to right. Before inserting x, prefix(rank(x)) is how many earlier values are at most x, so seen - prefix(rank(x)) of the earlier values are greater than x. Add that, then add(rank(x), 1). Total O(n log n).

When values are large or negative, compress them first: sort the distinct values and map each to its position plus 1. This keeps the tree size equal to the number of distinct values.

The limit: range sum(l, r) relies on subtraction, prefix(r) - prefix(l - 1). That works for sum and xor, which can be undone, but not for min, max or gcd over an arbitrary range. For those, or for range assignments, use a segment tree.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Explain the lowbit index trick~45m
  2. 2
    Implement point update~45m
  3. 3
    Implement prefix and range queries~45m
  4. 4
    Count inversions with a Fenwick tree~45m

Key points

  • Update walks up with i += i & -i; query walks down with i -= i & -i.
  • Indexes are 1-based to make the lowbit trick work.
  • Range sum(l, r) = prefix(r) - prefix(l - 1).
  • Counting inversions with a Fenwick tree is O(n log n).

Key terms

Tap a card to flip it. 0/3 known

Examples

python
class Fenwick:
    def __init__(self, n):
        self.t = [0] * (n + 1)

    def add(self, i, delta):      # 1-based, O(log n)
        while i < len(self.t):
            self.t[i] += delta
            i += i & -i

    def prefix(self, i):          # sum of 1..i, O(log n)
        s = 0
        while i > 0:
            s += self.t[i]
            i -= i & -i
        return s

Range sums on a changing array

a = [3, 2, -1, 6, 5, 4, -3, 3] (positions 1 to 8). After the linear build, t = [3, 5, -1, 10, 5, 9, -3, 19]. Step 1: sum of positions 3 to 6 = prefix(6) - prefix(2). prefix(6) reads t[6] + t[4] = 9 + 10 = 19, and prefix(2) reads t[2] = 5, so the answer is 14 (check: -1 + 6 + 5 + 4 = 14). Step 2: add 2 to position 4. The update walk touches t[4] and t[8] only. Step 3: the same query now returns 21 - 5 = 16.

python
class BIT:
    def __init__(self, a):              # O(n) build, a is a normal list
        self.n = len(a); self.t = [0] + list(a)
        for i in range(1, self.n + 1):
            j = i + (i & -i)
            if j <= self.n: self.t[j] += self.t[i]
    def add(self, i, d):                # 1-based, O(log n)
        while i <= self.n: self.t[i] += d; i += i & -i
    def prefix(self, i):                # sum of a[1..i], O(log n)
        s = 0
        while i > 0: s += self.t[i]; i -= i & -i
        return s
    def range_sum(self, l, r): return self.prefix(r) - self.prefix(l - 1)
b = BIT([3, 2, -1, 6, 5, 4, -3, 3])
print(b.range_sum(3, 6)); b.add(4, 2); print(b.range_sum(3, 6))   # 14 16

Counting inversions in [3, 1, 2]

An inversion is a pair i < j with a[i] > a[j]. Ranks are 1 -> 1, 2 -> 2, 3 -> 3. Step 1: x = 3, nothing seen yet, add 0, then mark rank 3. Step 2: x = 1, one value seen, prefix(1) = 0 of them are at most 1, so 1 - 0 = 1 inversion. Mark rank 1. Step 3: x = 2, two seen, prefix(2) = 1 (the 1), so 2 - 1 = 1 more. Total 2: the pairs (3, 1) and (3, 2). For [8, 4, 2, 1] the same code returns 6, the maximum for 4 elements.

python
def inversions(a):                # O(n log n)
    rank = {v: i + 1 for i, v in enumerate(sorted(set(a)))}
    t, inv = [0] * (len(rank) + 1), 0
    for seen, x in enumerate(a):
        i, s = rank[x], 0
        while i > 0: s += t[i]; i -= i & -i      # earlier values <= x
        inv += seen - s                          # earlier values > x
        i = rank[x]
        while i < len(t): t[i] += 1; i += i & -i
    return inv

print(inversions([3, 1, 2]), inversions([8, 4, 2, 1]))   # 2 6

Quick reference

  • lowbit(i) = i & -i; t[i] holds the sum of a[i - lowbit(i) + 1 .. i] with 1-based indexes
  • Update: while i <= n: t[i] += d; i += i & -i (O(log n))
  • Query: while i > 0: s += t[i]; i -= i & -i (O(log n))
  • sum(l..r) = prefix(r) - prefix(l - 1)
  • Linear build: for each i, add t[i] into t[i + (i & -i)] when that index is at most n
  • To set a[i] = v, add v - a[i]; keep a plain copy of the array
  • Range add, point query: add(l, d), add(r + 1, -d), then a[i] = prefix(i)
  • Range min or max with updates is not a Fenwick job: use a segment tree

Common mistakes

  • Using index 0, which makes i & -i zero and loops forever.
  • Setting a value with add without subtracting the old value first.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What is lowbit(12), that is 12 & -12?

Question 2

2Which cells does prefix(13) read?

Question 3

3Why does the classic Fenwick tree use 1-based indexes?

Question 4

4Roughly how many cells does one point update touch when n = 1,000,000?

Question 5

5Which query can a single standard Fenwick tree not answer for any range [l, r] with updates?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    With n = 16, list the cells touched by add(5, d) and the cells read by prefix(11). Do it by hand using binary.

  2. Exercise 2medium

    Implement NumArray(nums) with update(index, val) that sets nums[index] = val and sumRange(left, right), both inclusive and 0-based, each in O(log n).

  3. Exercise 3hard

    Count of smaller numbers after self: for each element, count how many elements to its right are strictly smaller. [5, 2, 6, 1] gives [2, 1, 1, 0]. Aim for O(n log n).

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is a Fenwick tree better than a segment tree?
For prefix sums with point updates it is shorter, uses less memory and is usually faster. A segment tree is more flexible: it handles min, max, gcd and range updates with lazy propagation.
Why is it called a tree if it is just an array?
The blocks each cell covers nest inside each other, and following i += i & -i from any cell leads to its parent. That parent relation forms a tree, stored implicitly in a flat array.
Can I use a Fenwick tree with 0-based indexes?
Yes. A common 0-based variant uses i = i | (i + 1) for updates and r = (r & (r + 1)) - 1 for queries. Many people simply shift indexes by one and keep the classic 1-based version.
What is the time to build a Fenwick tree?
O(n log n) if you call add for each element, or O(n) with the linear build that pushes each cell into its parent once.

Go deeper

ShareXLinkedInWhatsApp