Segment Trees for Range Sums
Track which stored segments contribute to a query and which ancestors change after an update.
Core Intuition & How It Works
A segment tree is a binary tree over an array where each node stores an aggregate (sum, min, or max) of a contiguous subrange. It supports both point updates and arbitrary range queries in O(log n) time.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n) build, O(log n) query/update |
| Space Complexity | O(n) (4n array) |
| Topic Chapter | Chapter 7: Trees |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Split every query into total overlap (return node), no overlap (return identity), and partial overlap (recurse on both halves).
Common Pitfalls & Edge Cases
Returning 0 as the identity element for range-minimum queries instead of +Infinity, or under-allocating the tree array below 4n.
Real-World & Technical Interview Applications
Dynamic range sums/min/max, competitive programming, interval analytics, and computational geometry.