The problem
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.
Segment trees
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).
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.
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.
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).
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).
Fenwick trees
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.
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).
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].
Choosing
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.
What happens
;; step 1/10 · range-sums 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)
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.