Segment Trees and Fenwick Trees
Answer range queries with point or range updates in O(log n): advanced, but useful for competitive programming and top-tier OAs.
Advanced · about 7 hours · difficulty 5/5
Learn first: Prefix Sums and Difference Arrays, Binary Tree Traversals
Prefix sums break as soon as values change. Segment trees and Fenwick trees support both updates and range queries in O(log n). They are rarely asked in normal interviews but appear in harder OAs and contests.
Fenwick tree (Binary Indexed Tree)
- Supports point update and prefix sum in O(log n) with very short code using i & (-i).
- Range sum = prefix(r) - prefix(l - 1).
- Also counts inversions and "count of smaller numbers after self" with coordinate compression.
Segment tree
- Each node stores an answer (sum, min, max, gcd) for a range; size about 4n.
- Build in O(n), query and point update in O(log n).
- Lazy propagation handles range updates (add v to all of [l, r]) in O(log n).
When to use what
- Static array, many range sums: prefix sums.
- Updates plus sum queries: Fenwick tree.
- Updates plus min, max or custom merges, or range updates: segment tree.
Classic problems
Range Sum Query - Mutable, Count of Smaller Numbers After Self, Count Inversions (BIT version), Dynamic Range Sum Queries and Dynamic Range Minimum Queries (CSES), Range Update Queries (CSES).
Pitfalls
- Fenwick trees are 1-indexed; an index of 0 loops forever.
- Forgetting to push lazy values down before recursing.
You are ready to move on when you can implement a segment tree for range minimum with point updates and explain when a Fenwick tree is enough.
Key concepts
- Fenwick tree point update and prefix query
- Segment tree build, query, update
- Custom merge functions
- Lazy propagation
- Coordinate compression
- Sparse table for static RMQ
Mini project
Implement a Fenwick tree and a segment tree (with lazy propagation) as reusable templates, then solve: Range Sum Query - Mutable, Count of Smaller Numbers After Self, Dynamic Range Sum Queries (CSES), Dynamic Range Minimum Queries (CSES), Range Update Queries (CSES). Log time and pattern.
Check yourself
Why does a segment tree need about 4n nodes, and what does lazy propagation postpone?
Free resources
- cp-algorithms: Segment tree (cp-algorithms)
- cp-algorithms: Fenwick tree (cp-algorithms)
- Codeforces EDU: Segment Tree (Codeforces)