Introduction
Range query data structures are fundamental in competitive programming for efficiently answering queries over array segments. These structures support operations like:- Range Sum/Min/Max: Find aggregate values over a range
- Range Updates: Modify multiple elements efficiently
- Point Queries: Access individual elements after updates
Segment Tree
Versatile tree structure supporting range queries and updates in O(log n)
Fenwick Tree
Memory-efficient structure for prefix sums and point updates
Sparse Table
Static RMQ with O(1) query time for idempotent operations
Choosing the Right Structure
Segment Tree
- Best for: General range queries with range updates
- Supports: Any associative operation
- Updates: O(log n) point and range updates
- Queries: O(log n)
- Space: O(4n)
Fenwick Tree (BIT)
- Best for: Prefix sums and frequency counting
- Supports: Operations with inverse (addition/subtraction)
- Updates: O(log n) point updates
- Queries: O(log n) prefix queries
- Space: O(n)
Sparse Table
- Best for: Static arrays with idempotent operations
- Supports: min, max, gcd (operations where f(x,x) = x)
- Updates: Not supported (static)
- Queries: O(1)
- Space: O(n log n)
Common Use Cases
Idempotent Operations: An operation f is idempotent if f(x, x) = x. Examples include min, max, gcd, but NOT sum or xor.
Range Sum Queries
Range Minimum Query (RMQ)
Range Updates with Lazy Propagation
Performance Comparison
| Structure | Build | Point Update | Range Update | Point Query | Range Query | Space |
|---|---|---|---|---|---|---|
| Segment Tree | O(n) | O(log n) | O(log n) | O(log n) | O(log n) | O(4n) |
| Segment Tree (Lazy) | O(n) | O(log n) | O(log n) | O(log n) | O(log n) | O(4n) |
| Fenwick Tree | O(n log n) | O(log n) | - | O(log n) | O(log n) | O(n) |
| Sparse Table | O(n log n) | - | - | O(1) | O(1) | O(n log n) |
Next Steps
Explore specific implementations:- Segment Tree - Learn about basic and lazy propagation variants
- Fenwick Tree - Master efficient prefix sum queries
- Sparse Table - Understand O(1) RMQ for static arrays