Segment Trees & Fenwick Trees
Answer range queries on data that keeps changing in logarithmic time with Fenwick and segment trees, and know when a static prefix array is enough.
4 objectives 6 steps about 130 min
Check what you know
The lessons are coming later. The knowledge check is ready now.
This skill page is a public outline. Its lessons and knowledge check appear here as subject-matter experts approve them.
Learning objectives
- Implement a Fenwick (binary indexed) tree with point updates and prefix and range sums in O(log n), and explain how each index's lowest set bit fixes the block of values it stores.
- Implement a segment tree over an associative operation (sum, min, max, gcd) with point updates and range queries in O(log n), and extend it with lazy propagation for range-add updates.
- Choose among a prefix-sum array, a difference array, a Fenwick tree and a segment tree for a stated mix of queries and updates, and use a Fenwick tree over compressed values to count inversions.
- Answer static range-minimum queries in O(1) after O(n log n) preprocessing with a sparse table, explain why overlapping blocks work only for idempotent operations, and use square-root decomposition as a simpler O(sqrt n) structure for point updates and range queries.
Lesson plan
6 steps, about 130 min · 0 of 5 lessons available so far
- When the Array Keeps Changing Concept · 15 min · coming later
- Lab: A Fenwick Tree and Inversion Counting Lab · 30 min · coming later
- Segment Trees for Any Associative Operation Worked example · 30 min · coming later
- Deferring Work with Lazy Propagation Worked example · 20 min · coming later
- Static Ranges: Sparse Tables and Square-Root Blocks Worked example · 20 min · coming later
- Check: Range Query Problems Knowledge check · 8 questions
Practise it
Build a Fenwick tree and a segment tree with lazy range-add, verify both against a plain list over 10,000 random mixed updates and queries, then count inversions in a 100,000-element array and report the speed-up over the O(n^2) baseline. Finally, build a sparse table for range minimum and confirm its O(1) answers against the segment tree.
References
Hard prerequisites
Unlocks
Nothing depends on this skill yet.
On these roadmaps
Progress and evidence for this skill are shared across all of them.