Overview
Segment trees are one of the most powerful and flexible data structures in competitive programming. They support range queries and updates in O(log n) time for any associative operation.Time Complexity
- Build: O(n)
- Query: O(log n)
- Update: O(log n) for both point and range updates (with lazy propagation)
Basic Segment Tree
The basic segment tree supports point updates and range queries efficiently using a bottom-up approach.Implementation
range_query_segment_tree.cpp
Usage Examples
- Range Maximum Query
- Range Sum Query
- Range Minimum Query
Segment Tree with Lazy Propagation
Lazy propagation enables efficient range updates by deferring updates until necessary.Full Implementation
range_query_segment_tree_lazy_full.cpp
Usage Examples
- Range Assignment
- Multiple Range Updates
- Finding Min/Max Indices
Binary Search on Segment Tree
Segment trees support efficient binary search operations to find the first/last position satisfying a condition.Common Applications
Range Sum Queries
Track cumulative values with point or range updates
Range Min/Max Queries
Find extrema in ranges with dynamic updates
Coordinate Compression
Map large coordinate spaces to smaller ranges
2D Range Queries
Nested segment trees for 2D operations
Practice Problems
- Range Sum Query - Mutable (LeetCode 307)
- Range Minimum Query (CSES)
- Dynamic Range Sum Queries (CSES)
- Hotel Queries (CSES) - Binary search on segment tree
See Also
- Fenwick Tree - More efficient for prefix sums
- Sparse Table - O(1) queries for static arrays