Module 11 · Bits, Range Tools and Final Review · Lesson 38 of 40
Range tools: segment trees and Fenwick trees
When numbers keep changing and you keep asking for range sums, prefix sums are too slow. Meet two O(log n) helpers.
In this lesson · about 18 minutes
- Explain why prefix sums struggle when values change
- Describe what a segment tree and a Fenwick tree store
- Choose between them
In Module 4, prefix sums answered "sum from a to b" in O(1). But they have a weakness: if one number changes, every prefix after it must be fixed, which is O(n). If changes and questions keep mixing, we need a better tool.
| Tool | Change one value | Range question |
|---|---|---|
| Plain list | O(1) | O(n) |
| Prefix sums | O(n) | O(1) |
| Fenwick tree / segment tree | O(log n) | O(log n) |
Segment tree
A binary tree where each node stores the answer (like the sum) for a range of the list. The root covers everything; its children cover the left and right halves; leaves cover single items. To answer a range question, combine a few nodes whose ranges fit inside it, about 2 log n of them. To change a value, update the leaf and the nodes above it: log n of them.
Segment trees are flexible: they can store sums, minimums, maximums or other combined facts about a range.
Fenwick tree (binary indexed tree)
A clever list where each box stores the sum of a block of items whose size is set by the lowest 1-bit of its index (the i & -i trick from the bits lesson). It handles "change a value" and "prefix sum" in O(log n) with very short code, but it's best for sums.
def update(tree, i, delta): # tree is 1-indexed, size n + 1
while i < len(tree):
tree[i] += delta
i += i & -i
def prefix(tree, i): # sum of items 1..i
total = 0
while i > 0:
total += tree[i]
i -= i & -i
return total
Which one?
- Only sums with point changes: Fenwick (shorter code).
- Min, max, or more complex range facts: segment tree.
- No changes at all: plain prefix sums.
Try it: a Fenwick tree
Check your understanding0 of 2 correct
Quiz score: 0 of 2
Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.