Segment trees and Fenwick trees
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.
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)
Read the lesson step by step
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)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 timesEach 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) = 3A 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: 0Whole 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) workA 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 32Fenwick: 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] = 43Prefix 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 = 32A 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: stopWhich 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)
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01In the heap-style segment tree for 8 items (root t[1], children 2v and 2v + 1), which slice of a does t[6] cover?
Level 2 holds t[4] to t[7], each covering 2 items: t[4] = a[0:2], t[5] = a[2:4], t[6] = a[4:6], t[7] = a[6:8].
02A query reaches a node whose slice is only partly inside the range it is summing. What does it do?
Outside gives 0, fully inside gives the stored sum, and partly inside splits: the node asks its two children, which cover the two halves of its slice.
03You set one item of a list of n = 1024 numbers in a segment tree. How many stored sums change?
Only the nodes on the path from that leaf to the root contain the item: one per level. 1024 leaves give log₂ 1024 + 1 = 11 levels, so 11 nodes.
04In a Fenwick tree, prefix(12) adds F[i] and then does i -= i & -i. Which F entries does it add?
12 is 1100 in binary, so 12 & -12 = 4 and i becomes 8 (1000); 8 & -8 = 8 and i becomes 0. F[12] holds sum(a[8:12]) and F[8] holds sum(a[0:8]).
05You need the minimum of any range a[l:r] while items keep changing. Which structure fits?
A segment tree works for any operation that combines two children, such as min. The Fenwick trick of subtracting two prefixes needs an undo, and there is no way to subtract a minimum.
Glossary
- Range sum
- The total of a slice of a list, such as sum(a[1:7]): items 1 to 6.
- Slice a[l:r]
- In Python, the items with index k where l ≤ k < r.
- Segment tree
- A binary tree whose leaves are the items of a list and whose every other node stores the sum (or minimum, or maximum) of the slice below it.
- Leaf
- A node with no children. Here each leaf holds one item of the list.
- Fenwick tree
- Also called a binary indexed tree. A list F[1..n] where F[i] holds the sum of the i & -i items that end at position i. It supports prefix sums and changes in O(log n).
- Lowest 1 bit (i & -i)
- The value of the rightmost 1 in i's binary form: 6 (110) gives 2, 8 (1000) gives 8.
- Prefix sum
- The total of the first i items, sum(a[0:i]). A range sum is the difference of two prefix sums.
- Augmentation
- Storing extra data at each node of a tree, computed from its children, and keeping it correct after every change.
Notes and sources
- The segment tree here is stored like a heap: the root is t[1] and node v has children 2v and 2v + 1, so the leaves t[n..2n − 1] are a itself. That needs n to be a power of two; for other n, pad a with zeros, or use the recursive version in Sedgewick and Wayne's SegmentTree.java.
- Why at most two whole nodes per level: the nodes a query takes on one level are side by side, and two side-by-side nodes with the same parent would have been taken as that parent instead. So only the two ends of the slice can need a node at each level. The tests check every one of the 36 slices of a.
- The Fenwick tree is named after Peter Fenwick, who published it in 1994 for cumulative frequency tables; Boris Ryabko described an earlier form in 1989. It is also called a binary indexed tree. It counts from 1, so F[0] is unused and add() shifts the 0-based index by one.
- i & -i keeps only the lowest 1 bit of i: Python works out bitwise operations as if in two's complement with infinitely many sign bits, so for 6 (binary 110) it gives 2 (binary 10).
- The code in the step details is real Python 3. The tests run it under python3 and check every sum, every path and every stored value in the figure.
- Sedgewick and Wayne, Algorithms 4th ed., code: SegmentTree.java
- Sedgewick and Wayne, Algorithms 4th ed., code: FenwickTree.java
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 7: Binary Trees II: AVL (subtree augmentation)
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 17: Augmenting Data Structures
- Fenwick tree (history, including Fenwick 1994 and Ryabko 1989)
- Python Standard Library: Built-in Types (slices and bitwise operations on integers)
Quiz Unlocks after the last step.