Segment Trees & Fenwick Trees
Range queries and updates in O(log n).
An array of a million sensor readings keeps changing, and you must answer "what is the sum, or the minimum, of readings through ?" thousands of times a second. Rescanning costs up to a million steps per question; a prefix-sum array answers in one step but must be rebuilt after every change. A segment tree does both in a few dozen steps, and a Fenwick tree does sums with two three-line loops.
What you’ll learn
- Compare naive scans, prefix sums, square-root decomposition and trees for range queries with updates, and pick the lightest one that fits.
- Build a segment tree for any associative operation, answer range queries and point updates in , and prove that a query visits at most four nodes per level.
- Implement the iterative bottom-up segment tree, and descend a segment tree to find the first index with a property in .
- Implement a Fenwick tree with lowest-set-bit jumps for prefix sums and point updates, and turn it into range updates with point queries.
- Recognize range-query problems, including inversion counting and "smaller elements to the right" with a Fenwick tree over compressed values.
Range queries meet updates
The problem: an array and a stream of two kinds of operations, mixed in any order:
- update: set ;
- range query: report the sum (or minimum, maximum, gcd, …) of , inclusive.
Each classic structure makes one of the two cheap:
| Approach | update | query | Idea |
|---|---|---|---|
| Scan the range | store nothing | ||
| Prefix sums | ; an update shifts every later prefix | ||
| Square-root decomposition | blocks of about elements, each with its stored sum | ||
| Segment tree | stored answers for halves, quarters, eighths, … | ||
| Fenwick tree | stored sums of ranges whose lengths are powers of two; sums only |
Square-root decomposition is the natural middle ground. Cut the array into blocks of elements and store each block's sum. A query adds the at most elements in the two partial end blocks and at most whole block sums; an update changes one element and one block sum. The query cost is smallest at . It is simple and flexible, and the Optimal lesson Sparse Tables & Square-Root Decomposition develops it; for plain range queries with updates, trees do better.
An array of numbers never changes, and you must answer range-sum queries. Which structure is both the simplest and the fastest here?
- A segment tree
- A Fenwick tree
- A prefix-sum array
- Square-root decomposition
Show the answer
C. A prefix-sum array
Without updates, one pass computes , and each query is in : in total. Trees pay per query for the ability to absorb updates, which this problem never uses.
The segment tree
class SegTree: # range sums; any associative op works
def __init__(self, a):
self.n = len(a)
self.t = [0] * (4 * self.n) # node 1 = root; children 2v and 2v + 1
self._build(a, 1, 0, self.n - 1)
def _build(self, a, v, l, r): # O(n): each node once
if l == r:
self.t[v] = a[l]; return
m = (l + r) // 2
self._build(a, 2 * v, l, m); self._build(a, 2 * v + 1, m + 1, r)
self.t[v] = self.t[2 * v] + self.t[2 * v + 1]
def query(self, ql, qr, v=1, l=0, r=None): # sum of a[ql..qr], inclusive: O(log n)
if r is None: r = self.n - 1
if qr < l or r < ql:
return 0 # disjoint: skip, return the identity
if ql <= l and r <= qr:
return self.t[v] # inside: take the whole node
m = (l + r) // 2 # partial overlap: split
return self.query(ql, qr, 2 * v, l, m) + self.query(ql, qr, 2 * v + 1, m + 1, r)
def update(self, i, x, v=1, l=0, r=None): # a[i] = x: O(log n), one root-leaf path
if r is None: r = self.n - 1
if l == r:
self.t[v] = x; return
m = (l + r) // 2
if i <= m: self.update(i, x, 2 * v, l, m)
else: self.update(i, x, 2 * v + 1, m + 1, r)
self.t[v] = self.t[2 * v] + self.t[2 * v + 1]The textbook recursive version. A query meets three cases at every node: disjoint (skip it), inside (take its stored value), partial (split into both children). An update walks to one leaf and recomputes every node on the way back up.
On the array , which nodes does the query for the sum of take whole?
- Node 5, covering , and node 3, covering :
- Nodes 5, 6 and 7, covering , and
- The six leaves from to
- The root, minus node 4, covering
Show the answer
A. Node 5, covering , and node 3, covering :
The root splits; node 2 splits; node 4 is disjoint and skipped; node 5 is inside and taken; node 3 is inside and taken. So , and the answer is . A query always takes the largest nodes that fit.
Why every query costs O(log n)
The nodes of one level cover disjoint intervals in left-to-right order. A node is split only when it partly overlaps , so it contains one element inside the range and one outside: it straddles the left boundary (contains and ) or the right one (contains and ). At most one node per level straddles each boundary:
Every visited node except the root is a child of a split node, so the visits on one level are at most twice the splits on the level above:
Summing over the levels bounds the work. For a power of two the exact maximum is visited nodes: 11 for , as the widget's range shows.
An array has elements. At most how many segment-tree nodes can one range query visit, counting the skipped ones?
Show the answer
15 nodes
of the 31 nodes: the root, then up to 4 nodes on each of the 4 levels below it, except that the second level has only 2 nodes. A query over a range like meets both boundaries on every level down to the leaves.
Any associative operation. Nothing in the proof uses addition. Each node needs an associative operation with an identity element, a monoid: sum (0), minimum (), maximum (), gcd (0), xor (0), or a pair such as "maximum and how often it occurs". Commutativity is not needed, provided results are always combined left before right; matrix products, which compose functions along the array, work too.
The iterative version. In contests, the bottom-up tree below is shorter and faster: the leaves live at , node has children and , and a query climbs from both ends of a half-open range toward the root. It works for every , not only powers of two.
#include <vector>
using namespace std;
struct SegTree { // range sums; swap op and ID for min, max, gcd, ...
int n;
vector<long long> t; // leaves at t[n .. 2n-1]; node i has children 2i, 2i+1
static long long op(long long a, long long b) { return a + b; }
static constexpr long long ID = 0; // identity of op
explicit SegTree(const vector<long long>& a) : n((int)a.size()), t(2 * a.size(), ID) {
for (int i = 0; i < n; ++i) t[n + i] = a[i];
for (int i = n - 1; i >= 1; --i) t[i] = op(t[2 * i], t[2 * i + 1]); // O(n)
}
void set(int i, long long x) { // a[i] = x: O(log n)
for (t[i += n] = x; i > 1; i >>= 1) t[i >> 1] = op(t[i & ~1], t[i | 1]);
}
long long query(int l, int r) const { // op over a[l .. r-1], half-open: O(log n)
long long resl = ID, resr = ID; // two sides keep left-to-right order
for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
if (l & 1) resl = op(resl, t[l++]);
if (r & 1) resr = op(t[--r], resr);
}
return op(resl, resr);
}
};Half the memory of the recursive layout and no recursion. On each level the query takes the node at the left end if it is a right child, and the node just before the right end if that one is a left child, then moves both ends up a level. The two accumulators make it correct even for non-commutative operations.
Descending the tree. Many questions ask for a position, not a value: the first index with , or the first prefix whose sum reaches . Walk down, entering a subtree only if its stored value says the answer can be inside. Each level costs beyond the nodes an ordinary query would visit, so the search is , against for a binary search that calls query at every step.
def first_at_least(t, ql, x, v, l, r): # t: a max-tree in the recursive layout
"""Smallest i >= ql with a[i] >= x in node v's range [l, r], or -1. O(log n)."""
if r < ql or t[v] < x:
return -1 # nothing usable here: prune the subtree
if l == r:
return l
m = (l + r) // 2
i = first_at_least(t, ql, x, 2 * v, l, m)
return i if i != -1 else first_at_least(t, ql, x, 2 * v + 1, m + 1, r)Call it as first_at_least(t, ql, x, 1, 0, n - 1). Typical uses: the first seat row with at least free seats, or the first bin that can still hold an item.
Fenwick trees
- Prefix sum : add , then clear the lowest set bit of and repeat until . For example , since : one read per 1-bit of .
- Point update : add to , then add the lowest set bit to and repeat while ; this visits exactly the entries whose ranges contain .
- Range sum of positions : .
Both loops run at most times. The Optimal lesson Fenwick Trees in Depth proves why the ranges fit together.
class Fenwick: # 1-indexed: f[p] = a[p - lowbit(p) + 1] + ... + a[p]
def __init__(self, n):
self.n, self.f = n, [0] * (n + 1)
def add(self, p, delta): # a[p] += delta: O(log n)
while p <= self.n:
self.f[p] += delta
p += p & -p # next range that contains position p
def prefix(self, p): # a[1] + ... + a[p]: O(log n)
s = 0
while p > 0:
s += self.f[p]
p -= p & -p # drop the lowest set bit
return s
def range_sum(self, l, r): # a[l] + ... + a[r], inclusive, 1-indexed
return self.prefix(r) - self.prefix(l - 1)entries instead of or , two three-line loops, and fast in practice. To set , keep a copy of the array and add .
Range answers come from subtracting two prefixes, so a Fenwick tree needs an invertible operation: sums, xor, counts. Range minimum or maximum needs a segment tree, or a sparse table if the array never changes.
Range update, point query. Store the difference array instead: adding to positions becomes add(l, v) and add(r + 1, -v), and the current value at position is prefix(p). Range updates with range sums need a second Fenwick tree, derived in Fenwick Trees in Depth, or a segment tree with lazy propagation.
Which positions does the Fenwick entry cover?
- Only position 12
- Positions 9 to 12
- Positions 1 to 12
- Positions 5 to 12
Show the answer
B. Positions 9 to 12
, so , and covers . Entries with odd indices cover one position, multiples of 4 that are not multiples of 8 cover four, and so on.
Recognizing it
Reach for a segment tree or a Fenwick tree when:
- range questions (sum, minimum, maximum, gcd, count) are interleaved with updates, and and are around to , so that per operation fits and does not;
- a scan asks "how many earlier (or later) elements are smaller, larger, or inside a value range": keep a Fenwick tree over the values, after coordinate compression if they are large;
- offline points and queries can be sorted by one coordinate while a Fenwick tree counts along the other;
- a query asks for a position: the first index with a property, or the -th smallest stored value.
| Problem (in brief) | Key idea | Cost |
|---|---|---|
| Point updates and range sums | Fenwick tree | per operation |
| Point updates and range minimum | Segment tree with and identity | per operation |
| Count the inversions, or for each element the smaller elements to its right | Scan, querying and inserting ranks in a Fenwick tree over compressed values | |
| The first index with , under updates | Max segment tree, then descend | per operation |
| Add to many times, reading single elements in between | Fenwick tree over the difference array | per operation |
def count_inversions(a): # pairs i < j with a[i] > a[j]: O(n log n)
rank = {v: k + 1 for k, v in enumerate(sorted(set(a)))} # coordinate compression
fw, inv = Fenwick(len(rank)), 0
for i, x in enumerate(a): # fw counts the values seen so far
inv += i - fw.prefix(rank[x]) # earlier values strictly greater than x
fw.add(rank[x], 1)
return invFor it returns 3: the pairs , and . Scanning from the right and counting smaller values instead answers "how many smaller elements lie to the right of each element".
An array of integers receives operations in any order: "set " and "report the minimum of ". Which structure fits?
- A Fenwick tree
- A sparse table
- A prefix-minimum array
- A segment tree storing minimums
Show the answer
D. A segment tree storing minimums
Minimum is associative with identity , so a segment tree answers each query and update in . With depth , a query visits at most about 70 nodes, so all the operations together take roughly node visits, far within limits.
Key takeaways
- Prefix sums answer static range sums in but pay per update; square-root decomposition balances both at ; segment and Fenwick trees make both .
- A segment tree stores the operation's result for halves, quarters, … of the array. A query splits at most 2 and visits at most 4 nodes per level, so queries and point updates cost for any associative operation with an identity.
- The iterative tree keeps the leaves at and works for every ; descending a tree of maximums finds the first index with in .
- A Fenwick tree stores the sums of the ranges : prefix queries clear the lowest set bit, updates add it. It uses entries and a few lines of code, but only for invertible operations such as sums.
- Signals: many range queries mixed with updates; counts of earlier or later smaller elements, over compressed values; range additions with point reads, through a Fenwick tree over differences.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why does a segment-tree range query split at most two nodes on each level?
- Because the tree is balanced
- Because a split node only partly overlaps , so it straddles one of the range's two boundaries, and the nodes of one level are disjoint
- Because each node has exactly two children
- Because a query stops as soon as it reaches a leaf
Show the answer
B. Because a split node only partly overlaps , so it straddles one of the range's two boundaries, and the nodes of one level are disjoint
A node that partly overlaps contains an element inside the range and one outside, so it contains and , or and . The nodes of one level cover disjoint intervals, so at most one contains each boundary: at most 2 split nodes, and at most 4 visited nodes, per level.
In a Fenwick tree, which entries does prefix(13) add up?
Show the answer
C.
; dropping the lowest set bit repeatedly gives , then , then 0. The ranges , and partition : three reads, one per 1-bit of 13.
Why can't a plain Fenwick tree answer the minimum of an arbitrary range ?
- It answers a range by subtracting two prefix results, and minimum has no inverse
- Its entries are too small to hold minimums
- It is 1-indexed
- Minimum is not associative
Show the answer
A. It answers a range by subtracting two prefix results, and minimum has no inverse
works because addition can be undone. Knowing and does not determine . Use a segment tree, or a sparse table if the array never changes.
To count inversions, you scan from left to right with a Fenwick tree over the compressed values and, before inserting , add . What does that term count?
- The earlier elements smaller than or equal to
- The later elements smaller than
- The elements equal to
- The earlier elements strictly greater than
Show the answer
D. The earlier elements strictly greater than
After insertions the tree counts by value, and counts those . The other are greater: each forms an inversion with . Summing over counts every inversion once, in .
Go deeper
- Lazy Propagation · Range updates by deferring work: composing tags, and segment tree beats.
- Fenwick Trees in Depth · Lowest set bits, range updates and 2-D Fenwick trees.
- Sparse Tables & Square-Root Decomposition · Range minimum in O(1) per query, Mo’s algorithm, and the optimal RMQ structure.
Further reading
- P. M. Fenwick, "A new data structure for cumulative frequency tables," Software: Practice and Experience 24(3) (1994), 327–336.
- A. Laaksonen, Competitive Programmer's Handbook (2018), chapters 9 and 28.
- CP-Algorithms, Segment Tree and Fenwick Tree.
- S. Halim, F. Halim & S. Effendy, Competitive Programming 4 (2020), book 1, chapter 2.