ENع
←Segment and Fenwick trees
Lesson S1 · Special topics

Segment trees and Fenwick trees

15 min10 steps5 questionsIntermediate
About this lesson

Prefix sums answer a range sum in O(1), but one change to the list can rewrite every prefix. A segment tree stores the sum of a slice at every node, so a range sum adds a few whole nodes and a change fixes one path to the root: both O(log n). Build one over a = [5, 8, 6, 3, 2, 7, 2, 6], answer sum(a[1:7]), change a[4], then drop every right child to get the shorter Fenwick tree and walk it with i & -i. The lesson "Prefix sums" covers the O(1) query this builds on, and "Binary heaps: sift up and sift down" covers storing a tree in a list.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig S1 · Interactive
01 / 10

Sums over a changing list

The list a holds 8 numbers. We want sums of slices, like sum(a[1:7]), while values keep changing. Adding up a slice costs O(n) every time. Prefix sums answer in O(1), but one change can rewrite n of them.

a = [5, 8, 6, 3, 2, 7, 2, 6]
sum(a[1:7]) = 8 + 6 + 3 + 2 + 7 + 2 = 28

a[l:r] means items l, l + 1, ..., r - 1
loop over the slice:  query O(n), change O(1)
prefix sums:          query O(1), change O(n)
goal:                 both O(log n)
Loading figure…
or ← →
Read the lesson step by step
  1. Sums over a changing list

    The list a holds 8 numbers. We want sums of slices, like sum(a[1:7]), while values keep changing. Adding up a slice costs O(n) every time. Prefix sums answer in O(1), but one change can rewrite n of them.

    a = [5, 8, 6, 3, 2, 7, 2, 6]
    sum(a[1:7]) = 8 + 6 + 3 + 2 + 7 + 2 = 28
    
    a[l:r] means items l, l + 1, ..., r - 1
    loop over the slice:  query O(n), change O(1)
    prefix sums:          query O(1), change O(n)
    goal:                 both O(log n)
  2. Parents store sums

    A segment tree puts the 8 values in leaves. Each parent stores the sum of its two children: t[v] = t[2v] + t[2v + 1]. The root holds the total, 39. 8 leaves need 15 nodes, built in O(n).

    def build(a):
        n = len(a)                    # a power of two here
        t = [0] * n + list(a)         # leaves: t[n] .. t[2n - 1]
        for v in range(n - 1, 0, -1):
            t[v] = t[2 * v] + t[2 * v + 1]
        return t
    
    t[4..7] = 13, 9, 9, 8
    t[2..3] = 22, 17
    t[1]    = 39  (the total)
    nodes: 2n - 1 = 15; the loop runs n - 1 = 7 times
  3. Each node owns a slice

    Every node owns a slice of a, printed on its front. The root owns a[0:8], its children a[0:4] and a[4:8], and so on down to single items. Each level halves the slices, so 8 items need log₂ 8 = 3 levels below the root.

    node v covers a[lo:hi]; its children split it at mid = (lo + hi) // 2
      t[1]  a[0:8]   = 39
      t[2]  a[0:4]   = 22
      t[3]  a[4:8]   = 17
      t[4]  a[0:2]   = 13
      t[5]  a[2:4]   = 9
      t[6]  a[4:6]   = 9
      t[7]  a[6:8]   = 8
      t[8..15] are the single items a[0] .. a[7]
    levels below the root: log2(8) = 3
  4. A query splits partial nodes

    To get sum(a[1:7]), start at the root. Three cases: a node outside 1:7 gives 0; a node fully inside gives its stored sum; a node partly inside asks both children. The root, a[0:4], a[4:8], a[0:2] and a[6:8] are only partly inside.

    def query(t, l, r, v=1, lo=0, hi=None):
        if hi is None:
            hi = len(t) // 2          # node v covers a[lo:hi]
        if r <= lo or hi <= l:
            return 0                  # no overlap
        if l <= lo and hi <= r:
            return t[v]               # fully inside: take it
        mid = (lo + hi) // 2          # partly inside: ask both children
        return query(t, l, r, 2 * v, lo, mid) + query(t, l, r, 2 * v + 1, mid, hi)
    
      a[0:8]   partly inside: split
      a[0:4]   partly inside: split
      a[0:2]   partly inside: split
      a[0]     outside: 0
      a[1]     inside: take 8
      a[2:4]   inside: take 9
      a[4:8]   partly inside: split
      a[4:6]   inside: take 9
      a[6:8]   partly inside: split
      a[6]     inside: take 2
      a[7]     outside: 0
  5. Whole nodes add up

    Four nodes lie fully inside: a[1], a[2:4], a[4:6] and a[6]. Add them: 8 + 9 + 9 + 2 = 28, the same as the loop. Each level gives at most two whole nodes, so a query costs O(log n).

    query(t, 1, 7) = 8 + 9 + 9 + 2 = 28
    nodes taken: a[1], a[2:4], a[4:6], a[6]
    nodes visited: 11 of 15
    
    at most 2 whole nodes per level, at most 4 visited per level
    levels: log2(n) + 1, so O(log n) work
  6. A change fixes one path

    Set a[4] = 6 (it was 2). Only the nodes above that leaf contain it: a[4], a[4:6], a[4:8] and the root. Walk up, recomputing t[v] = t[2v] + t[2v + 1]. Each grows by 4. 4 nodes, one per level: O(log n).

    def update(t, i, x):
        v = len(t) // 2 + i
        t[v] = x
        while v > 1:
            v //= 2
            t[v] = t[2 * v] + t[2 * v + 1]
    
    
    update(t, 4, 6) walks v = 12 -> 6 -> 3 -> 1
      t[12]  a[4]     2 -> 6
      t[6]  a[4:6]   9 -> 13
      t[3]  a[4:8]   17 -> 21
      t[1]  a[0:8]   39 -> 43
    sum(a[1:7]) is now 32
  7. Fenwick: drop right children

    A Fenwick tree keeps only the root and every left child: 8 nodes for 8 items, in a list F[1..8]. F[i] is the node whose slice ends at i, so F[6] holds sum(a[4:6]) = 13. Its length is i & -i.

    def fenwick(a):
        F = [0] * (len(a) + 1)        # F[0] is unused
        for i, x in enumerate(a):
            add(F, i, x)
        return F
    
    F[i] = sum(a[i - (i & -i) : i])
      F[1]  i & -i = 1  a[0]     = 5
      F[2]  i & -i = 2  a[0:2]   = 13
      F[3]  i & -i = 1  a[2]     = 6
      F[4]  i & -i = 4  a[0:4]   = 22
      F[5]  i & -i = 1  a[4]     = 6
      F[6]  i & -i = 2  a[4:6]   = 13
      F[7]  i & -i = 1  a[6]     = 2
      F[8]  i & -i = 8  a[0:8]   = 43
  8. Prefix sums by jumping down

    prefix(7) = sum(a[0:7]). From i = 7, add F[i], then drop the lowest 1 bit: i -= i & -i. 7 → 6 → 4 → 0. Three nodes: 2 + 13 + 22 = 37. A range is two prefixes: prefix(7) − prefix(1).

    def prefix(F, i):                 # sum(a[0:i])
        s = 0
        while i > 0:
            s += F[i]
            i -= i & -i               # drop the lowest 1 bit
        return s
    
      i = 7 (0111)  add F[7] = 2, i -= 1
      i = 6 (0110)  add F[6] = 13, i -= 2
      i = 4 (0100)  add F[4] = 22, i -= 4
    prefix(7) = 37
    sum(a[1:7]) = prefix(7) - prefix(1) = 37 - 5 = 32
  9. A change climbs up

    add(F, 4, 3) adds 3 to a[4]. Start at i = 5 and add the lowest 1 bit: i += i & -i. 5 → 6 → 8. F[5], F[6] and F[8] each gain 3: the segment tree's path, minus the right child a[4:8].

    def add(F, i, d):                 # a[i] += d
        i += 1
        while i < len(F):
            F[i] += d
            i += i & -i               # add the lowest 1 bit
    
    
      i = 5 (0101)  F[5] 6 -> 9, i += 1
      i = 6 (0110)  F[6] 13 -> 16, i += 2
      i = 8 (1000)  F[8] 43 -> 46, i += 8
      i = 16 > 8: stop
  10. Which one to use

    Both answer a range sum and apply a change in O(log n). A Fenwick tree is shorter and needs n + 1 slots. A segment tree does more: it can also give the minimum or maximum of a range, which subtracting two prefixes cannot.

                     loop   prefix sums  segment tree  Fenwick
      range sum      O(n)   O(1)         O(log n)      O(log n)
      change one     O(1)   O(n)         O(log n)      O(log n)
      build          -      O(n)         O(n)          O(n log n) *
      slots          n      n + 1        2n            n + 1
    
    * with add(); an O(n) build also exists
    range min / max: segment tree yes, Fenwick no (no subtraction)

Quiz Unlocks after the last step.