Simple Algorithm
Algorithms & Data Structures · Optimal · 24 min

Fenwick Trees in Depth

Lowest set bits, range updates and 2-D Fenwick trees.

A Fenwick tree is an array of nn numbers and two loops that add or subtract the lowest set bit of an index. Yet it answers prefix sums under updates in O(log⁡n)O(\log n), finds the kk-th smallest stored value without a binary search over queries, supports range updates with range sums, and extends to any number of dimensions. All of it follows from one fact about binary numbers.

What you’ll learn

  • Prove that the ranges read by a prefix query partition (0,p](0, p], and that an update visits exactly the ranges that contain its position.
  • Build a Fenwick tree in O(n)O(n), and find the smallest position whose prefix sum reaches kk in O(log⁡n)O(\log n) by binary lifting.
  • Derive range updates with range sums from two Fenwick trees, and extend the structure to two dimensions.
  • Place the structure in its history (Ryabko; Fenwick) and against the cell-probe lower bound for dynamic prefix sums.

Why the lowest set bit works

DerivationPrefix queries and updates
  1. (0,p]=⨆j(pj+1, pj],p0=p,pj+1=pj−lowbit(pj),#reads=popcount⁡(p)(0, p] = \bigsqcup_{j} \big(p_{j+1},\ p_j\big], \qquad p_0 = p,\quad p_{j+1} = p_j - \mathrm{lowbit}(p_j), \qquad \#\text{reads} = \operatorname{popcount}(p)

    Prefix. Clearing the lowest set bit of pp gives p−lowbit(p)p - \mathrm{lowbit}(p), exactly the left end of F[p]F[p]'s range, so the ranges read by the walk meet end to end and stop at 0, one per 1-bit of pp:

  2. p → p+lowbit(p) → ⋯ → (first index>n)p \ \to\ p + \mathrm{lowbit}(p) \ \to\ \cdots \ \to\ (\text{first index} > n)

    Update. Let p=j⋅2kp = j\cdot2^k with jj odd. A larger dyadic interval containing F[p]F[p]'s range, of length 2k′′>2k2^{k''} > 2^k, ends at the first multiple of 2k′′2^{k''} at or after pp. That multiple is p+2kp + 2^k for every k′′k'' up to the lowest set bit of p+2kp + 2^k, and the interval is a Fenwick range exactly when k′′k'' equals that bit. So the next range up the chain belongs to p+lowbit(p)p + \mathrm{lowbit}(p), and the update walk visits precisely the entries that contain the updated position:

  3. Tprefix, Tupdate ≤ ⌊log⁡2n⌋+1T_{\text{prefix}},\ T_{\text{update}}\ \le\ \lfloor\log_2 n\rfloor + 1

    Cost. The prefix walk removes a 1-bit per step; the update walk strictly raises the lowest set bit per step. Either way:

Predict before you look

In a Fenwick tree over n=1000n = 1000 positions, how many entries does a point update at position 1 write?

Show the answer

10 writes

The path is 1→2→4→⋯→5121 \to 2 \to 4 \to \cdots \to 512, and the next index, 10241024, exceeds 1000: ten writes. Each step doubles the lowest set bit, so no update on 1000 positions can write more than 10 entries.

Linear-time construction and binary lifting

Inserting nn values one by one costs O(nlog⁡n)O(n\log n). Linear time is possible because each entry has a parent, q=p+lowbit(p)q = p + \mathrm{lowbit}(p), the next range up its chain, and the children of qq, namely q−1,q−2,q−4,…,q−lowbit(q)/2q-1, q-2, q-4, \dots, q - \mathrm{lowbit}(q)/2, cover (q−lowbit(q), q−1](q - \mathrm{lowbit}(q),\ q - 1] exactly. So F[q]F[q] is a[q]a[q] plus its children's entries, and a single left-to-right pass, adding each finished entry into its parent, builds them all.

python
def build(a):                          # a[1..n] (a[0] unused) -> Fenwick array in O(n)
    n = len(a) - 1
    f = a[:]                           # f[p] starts as a[p]
    for p in range(1, n + 1):
        q = p + (p & -p)               # the parent: next range containing p's range
        if q <= n:
            f[q] += f[p]               # f[p] is complete: all its children are < p
    return f

def find(f, k):                        # smallest p with prefix(p) >= k; needs a[i] >= 0
    n = len(f) - 1
    pos, step = 0, 1 << (n.bit_length() - 1)   # largest power of two <= n
    while step:
        if pos + step <= n and f[pos + step] < k:
            pos += step                # f[pos + step] covers exactly (pos, pos + step]
            k -= f[pos]
        step >>= 1
    return pos + 1                     # prefix(pos) < k <= prefix(pos + 1); n + 1 if none

find is binary search done inside the tree: one entry per bit, O(log⁡n)O(\log n), against O(log⁡2n)O(\log^2 n) for a binary search that calls prefix at every probe. It needs non-negative values, so that prefix sums never decrease.

The kk-th smallest of a dynamic multiset. Store, at position vv, how many copies of the value vv are present (after coordinate compression if values are large). Insertion and deletion are add(v, ±1), and the kk-th smallest value is find(f, k). For the multiset {1,3,3,7,9}\{1, 3, 3, 7, 9\}, find returns 1, 3, 3, 7, 9 for k=1,…,5k = 1, \dots, 5: an order-statistic structure in a dozen lines, when the values come from a small universe.

Check your understanding

During find, why does F[pos+step]F[pos + step] cover exactly the positions (pos, pos+step](pos,\ pos + step]?

  1. Because pospos is a sum of larger powers of two, hence a multiple of 2⋅step2\cdot step, so lowbit(pos+step)=step\mathrm{lowbit}(pos + step) = step
  2. Because stepstep is always 1 at the end
  3. Because prefix sums are non-decreasing
  4. Because FF was built in O(n)O(n) time
Show the answer

A. Because pospos is a sum of larger powers of two, hence a multiple of 2⋅step2\cdot step, so lowbit(pos+step)=step\mathrm{lowbit}(pos + step) = step

The search adds powers of two in decreasing order, so when it considers stepstep, pospos consists of larger powers only and is a multiple of 2⋅step2\cdot step. Then pos+steppos + step has lowest set bit stepstep, and its range is (pos,pos+step](pos, pos + step]: one read tells whether the answer lies beyond pos+steppos + step.

Range updates with range sums: two trees

A Fenwick tree over the difference array dd, with ai=∑j≤idja_i = \sum_{j \le i} d_j, already turns range updates into two point updates and point queries into prefix sums. Range sums need the prefix sums of aa itself, and one more tree recovers them.

DerivationPrefix sums of a from two trees
  1. S(p)=∑i=1pai=∑i=1p∑j=1idj=∑j=1pdj (p−j+1)S(p) = \sum_{i=1}^{p} a_i = \sum_{i=1}^{p}\sum_{j=1}^{i} d_j = \sum_{j=1}^{p} d_j\,(p - j + 1)

    Expand the prefix sum of aa in terms of dd: the difference djd_j contributes to aj,aj+1,…,apa_j, a_{j+1}, \dots, a_p, that is, p−j+1p - j + 1 times.

  2. S(p)=(p+1)∑j=1pdj − ∑j=1pj djS(p) = (p + 1)\sum_{j=1}^{p} d_j\ -\ \sum_{j=1}^{p} j\,d_j

    Split off the part that depends on pp:

  3. B1:  +v at l,  −v at r+1,B2:  +l v at l,  −(r+1) v at r+1B_1{:}\ \ +v \text{ at } l,\ \ -v \text{ at } r+1, \qquad B_2{:}\ \ +l\,v \text{ at } l,\ \ -(r+1)\,v \text{ at } r+1

    So keep two Fenwick trees, B1B_1 over djd_j and B2B_2 over j djj\,d_j. Adding vv to a[l..r]a[l..r] changes dld_l by +v+v and dr+1d_{r+1} by −v-v, which is four point updates:

  4. S(p)=(p+1) B1.prefix(p)−B2.prefix(p),sum(l..r)=S(r)−S(l−1)S(p) = (p+1)\,B_1.\mathrm{prefix}(p) - B_2.\mathrm{prefix}(p), \qquad \mathrm{sum}(l..r) = S(r) - S(l-1)

    Every operation is a constant number of Fenwick operations, O(log⁡n)O(\log n) each:

python
class RangeFenwick:                    # range add, range sum; positions 1..n
    def __init__(self, n):
        self.n, self.b1, self.b2 = n, [0] * (n + 2), [0] * (n + 2)

    def _add(self, f, p, d):
        while p <= self.n:
            f[p] += d; p += p & -p

    def _pre(self, f, p):
        s = 0
        while p > 0:
            s += f[p]; p -= p & -p
        return s

    def range_add(self, l, r, v):      # a[l..r] += v
        self._add(self.b1, l, v);      self._add(self.b1, r + 1, -v)
        self._add(self.b2, l, l * v);  self._add(self.b2, r + 1, -(r + 1) * v)

    def range_sum(self, l, r):         # a[l] + ... + a[r]
        S = lambda p: (p + 1) * self._pre(self.b1, p) - self._pre(self.b2, p)
        return S(r) - S(l - 1)

Half the memory of a lazy segment tree and no recursion. It works because addition is invertible and the update's effect on prefix sums is a linear function of pp; range assignment or range minimum need lazy propagation instead.

Think first On an all-zero array with n=8n = 8, add 5 to positions 3 to 6. What do B1.prefix(4)B_1.\mathrm{prefix}(4) and B2.prefix(4)B_2.\mathrm{prefix}(4) hold, and what is S(4)S(4)?

B1B_1 holds +5+5 at 3 and −5-5 at 7, so B1.prefix(4)=5B_1.\mathrm{prefix}(4) = 5. B2B_2 holds 3⋅5=153\cdot5 = 15 at 3 and −7⋅5=−35-7\cdot5 = -35 at 7, so B2.prefix(4)=15B_2.\mathrm{prefix}(4) = 15. Then S(4)=5⋅5−15=10S(4) = 5\cdot5 - 15 = 10: positions 3 and 4 hold 5 each. Likewise S(8)=9⋅0−(15−35)=20S(8) = 9\cdot0 - (15 - 35) = 20, four positions of 5.

Two dimensions, history and limits

In two dimensions, F[x][y]F[x][y] covers the rectangle (x−lowbit(x), x]×(y−lowbit(y), y](x - \mathrm{lowbit}(x),\ x] \times (y - \mathrm{lowbit}(y),\ y], and both loops simply nest. A point update and a prefix-rectangle sum cost O(log⁡n⋅log⁡m)O(\log n\cdot\log m), any rectangle is four prefix rectangles by inclusion–exclusion, and dd dimensions cost O(log⁡dn)O(\log^d n) per operation. The price is O(nm)O(nm) memory; when all points and queries are known in advance, sorting by one coordinate and keeping a one-dimensional Fenwick tree over the other answers the same counting queries in O((n+q)log⁡n)O((n+q)\log n) time with linear memory.

python
class Fenwick2D:                       # point add, rectangle sum: O(log n log m)
    def __init__(self, n, m):
        self.n, self.m = n, m
        self.f = [[0] * (m + 1) for _ in range(n + 1)]

    def add(self, x, y, d):
        i = x
        while i <= self.n:
            j = y
            while j <= self.m:
                self.f[i][j] += d; j += j & -j
            i += i & -i

    def prefix(self, x, y):            # sum over [1..x] x [1..y]
        s, i = 0, x
        while i > 0:
            j = y
            while j > 0:
                s += self.f[i][j]; j -= j & -j
            i -= i & -i
        return s

A rectangle [x1..x2]×[y1..y2][x_1..x_2]\times[y_1..y_2] is prefix(x2, y2) - prefix(x1 - 1, y2) - prefix(x2, y1 - 1) + prefix(x1 - 1, y1 - 1).

Can anything beat O(log⁡n)O(\log n)? In the cell-probe model, which charges only for memory accesses and so covers every algorithm, maintaining prefix sums of word-sized numbers under updates needs Ω(log⁡n)\Omega(\log n) amortized time per operation, even with randomization (Pătraşcu & Demaine, 2004). The Fenwick tree is optimal up to a constant factor. With ±1\pm1 updates the bound drops to Θ(log⁡n/log⁡log⁡n)\Theta(\log n/\log\log n); the lessons 2-D Prefix Sums & Inclusion–Exclusion and Augmented Search Trees discuss both bounds.

Key takeaways

  • F[p]F[p] covers the dyadic interval (p−lowbit(p), p](p - \mathrm{lowbit}(p),\ p], and any two such intervals are nested or disjoint. Clearing lowest set bits splits a prefix into popcount⁡(p)\operatorname{popcount}(p) ranges; adding them climbs the chain of ranges that contain a position. Both walks are O(log⁡n)O(\log n).
  • Passing each finished entry to its parent p+lowbit(p)p + \mathrm{lowbit}(p) builds the tree in O(n)O(n); binary lifting finds the smallest pp with prefix(p)≥k\mathrm{prefix}(p) \ge k in O(log⁡n)O(\log n), because pospos stays a multiple of 2⋅step2\cdot step.
  • Range additions with range sums take two trees: S(p)=(p+1)∑j≤pdj−∑j≤pj djS(p) = (p+1)\sum_{j\le p} d_j - \sum_{j\le p} j\,d_j, so each update is four point updates and each sum two prefix pairs. In dd dimensions the loops nest, O(log⁡dn)O(\log^d n) per operation.
  • Ryabko (1989) and Fenwick (1994) invented the structure for adaptive arithmetic coding, and the cell-probe lower bound of Pătraşcu and Demaine shows that its O(log⁡n)O(\log n) is optimal for word-sized updates.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why does p & -p isolate the lowest set bit of pp in two's complement?

  1. Because −p-p is pp with every bit flipped, so the AND keeps the bits where both are 1
  2. Because −p=¬p+1-p = \lnot p + 1 agrees with pp on the lowest set bit and the zeros below it, and is the complement of pp above it
  3. Because the AND of any two numbers is a power of two
  4. Because the sign bit of −p-p masks every bit but one
Show the answer

B. Because −p=¬p+1-p = \lnot p + 1 agrees with pp on the lowest set bit and the zeros below it, and is the complement of pp above it

¬p\lnot p has 1s where pp has its trailing zeros and a 0 at its lowest set bit; adding 1 carries through those 1s and sets that bit. Above it nothing changes, so −p-p is the complement of pp there, and the AND keeps exactly the lowest set bit. For p=12=011002p = 12 = 01100_2: −12=…101002-12 = \dots10100_2, and 12&(−12)=001002=412 \mathbin{\&} (-12) = 00100_2 = 4.

Question 2

With two Fenwick trees, B1B_1 over djd_j and B2B_2 over j djj\,d_j, which point updates implement "add vv to a[l..r]a[l..r]"?

  1. B1B_1: +v+v at ll; B2B_2: +v+v at rr
  2. B1B_1: +v+v at every position from ll to rr
  3. B1B_1: +v+v at ll and −v-v at rr; B2B_2: +v+v at ll and −v-v at rr
  4. B1B_1: +v+v at ll and −v-v at r+1r+1; B2B_2: +l v+l\,v at ll and −(r+1) v-(r+1)\,v at r+1r+1
Show the answer

D. B1B_1: +v+v at ll and −v-v at r+1r+1; B2B_2: +l v+l\,v at ll and −(r+1) v-(r+1)\,v at r+1r+1

The update changes dld_l by +v+v and dr+1d_{r+1} by −v-v, and B2B_2 stores j djj\,d_j, so its changes are l vl\,v and −(r+1) v-(r+1)\,v. Then S(p)=(p+1)B1.prefix(p)−B2.prefix(p)S(p) = (p+1)B_1.\mathrm{prefix}(p) - B_2.\mathrm{prefix}(p) is correct for every pp.

Question 3

In a Fenwick tree over n=16n = 16 positions, which entries does an update at position 5 write?

  1. 5, 4
  2. 5, 7, 15
  3. 5, 6, 8, 16
  4. 5, 10, 20
Show the answer

C. 5, 6, 8, 16

5=1012→1102=6→10002=8→100002=165 = 101_2 \to 110_2 = 6 \to 1000_2 = 8 \to 10000_2 = 16, adding the lowest set bit each time. These are exactly the entries whose ranges contain position 5: (4,5](4, 5], (4,6](4, 6], (0,8](0, 8] and (0,16](0, 16].

Question 4

You need the smallest position whose prefix sum reaches kk, in a Fenwick tree over non-negative values. What does binary lifting cost, compared with binary search over prefix calls?

  1. O(log⁡n)O(\log n) against O(log⁡2n)O(\log^2 n): lifting reads one entry per bit instead of a whole prefix per probe
  2. Both cost O(log⁡n)O(\log n)
  3. O(1)O(1) against O(log⁡n)O(\log n)
  4. Lifting is O(n)O(n), since it may scan every entry
Show the answer

A. O(log⁡n)O(\log n) against O(log⁡2n)O(\log^2 n): lifting reads one entry per bit instead of a whole prefix per probe

Binary search makes O(log⁡n)O(\log n) probes, each a prefix query costing O(log⁡n)O(\log n). Lifting walks the bits from high to low and reads a single entry per bit, keeping the sum of everything to the left of pospos in hand.

Further reading

  • P. M. Fenwick, "A new data structure for cumulative frequency tables," Software: Practice and Experience 24(3) (1994), 327–336.
  • B. Ya. Ryabko, "A fast on-line adaptive code," IEEE Transactions on Information Theory 38(4) (1992), 1400–1404.
  • M. Pătraşcu & E. D. Demaine, "Tight bounds for the partial-sums problem," Proceedings of the 15th ACM-SIAM Symposium on Discrete Algorithms (SODA) (2004), 20–29.
  • CP-Algorithms, Fenwick Tree.