Segment Trees and Fenwick Trees
Answer range queries with point or range updates in O(log n) using segment trees and Binary Indexed Trees.
Advanced · about 8 hours · difficulty 5/5
Learn first: Prefix Sums and Difference Arrays, Bit Manipulation, Binary Trees and Traversals
Prefix sums answer range queries in O(1) but break as soon as the array changes. When you need both updates and range queries, use a segment tree or a Fenwick tree for O(log n) per operation. These are mostly for contests and harder product-company rounds, so treat them as optional for most placements.
Fenwick tree (Binary Indexed Tree)
A compact array where index i stores the sum of a range whose length is the lowest set bit of i (i & -i). Point update and prefix query each walk O(log n) indices. Simple to code in about 10 lines, but limited to invertible operations like sum and XOR.
Segment tree
A binary tree where each node stores an aggregate (sum, min, max, gcd) of a segment. Build is O(n), point update and range query are O(log n). It supports any associative operation.
- Lazy propagation defers range updates ("add v to [l, r]") until needed, keeping them O(log n).
- Store it in an array of size 4n with recursive build, query and update functions.
Typical uses
Range sum/min with updates, counting inversions, "count of smaller numbers after self", and offline queries sorted by coordinate after coordinate compression.
Good enough to move on: you can code a Fenwick tree from memory and a recursive sum segment tree with point updates.
Key concepts
- Fenwick tree point update, prefix query
- Segment tree build, query, update
- Min/max/gcd segment trees
- Lazy propagation
- Coordinate compression
- Sparse table for static RMQ
Mini project
Implement a Fenwick tree and a segment tree and verify both against brute force on random tests, then solve: Range Sum Query Mutable, Count of Smaller Numbers After Self, CSES Dynamic Range Sum Queries, CSES Dynamic Range Minimum Queries, and CSES Range Update Queries.
Check yourself
Why can a Fenwick tree answer range sum queries but not directly answer range minimum queries with arbitrary updates?
Free resources
- Segment Tree (cp-algorithms)
- Fenwick Tree (cp-algorithms)
- CSES Problem Set (Range Queries) (CSES)