Segment Trees
Why Segment Trees?
Segment trees answer range queries and handle point/range updates in O(log n) time. They’re essential for problems involving:- Range sum/min/max/GCD queries
- Range updates (add/set all elements)
- Count elements in range satisfying condition
Pattern Recognition Signals:
- “Query sum/min/max from L to R” → Segment tree
- “Update element at position i” → Segment tree with point update
- “Add x to all elements from L to R” → Lazy propagation
- “Count elements > k in range” → Merge sort tree or segment tree with sets
Basic Segment Tree (Point Update, Range Query)
Usage
Segment Tree for Different Operations
Change the combine function and identity element.Lazy Propagation (Range Updates)
When you need to update a range of elements, not just one. The Problem: Adding a value to all elements in range [L, R] would require O(R - L + 1) point updates, making it O(n) per update—too slow! The Insight: Don’t update immediately. Instead, store a “pending update” (lazy value) at a node. Only push it down to children when needed. How it works:- Range Update: When updating [L, R], if a node’s range is completely inside [L, R], mark it with a lazy value and return (don’t recurse)
- Push Down: Before accessing children, push the lazy value down to them
- Query: Same as before, but push down lazy values as you traverse
Range Set (Assignment) with Lazy
Pattern 1: Coordinate Compression + Segment Tree
Problem: Count distinct elements, or handle values up to 10^9.Pattern 2: Count Inversions with Segment Tree
Pattern 3: Range Queries Offline
Problem: Answer queries more efficiently by processing in smart order.Pattern 4: Segment Tree on Indices
Problem: Track positions where something is true.Pattern 5: 2D Segment Tree
For 2D range queries (less common, but powerful).Common Mistakes
Practice Problems
Beginner (1000-1300)
Intermediate (1300-1600)
Advanced (1600-1900)
Key Takeaways
O(log n) Queries
Both point updates and range queries in logarithmic time.
Lazy Propagation
Defer updates until needed for O(log n) range updates.
4n Space
Always allocate 4n space for the tree array.
Combine Function
Customize for sum, min, max, GCD, or any associative operation.
Next Up
Chapter 18: String Algorithms
Master hashing, KMP, Z-function, and Trie for string problems.