array_range_query
A high-performance, generic implementation of segment trees and lazy segment trees in Rust for efficient range queries and range updates.
Includes helpers for:
- Range sum, min, max queries
- Range add, range assignment (replace), and lazy propagation for sum/min/max
Features
- Generic Segment Tree (
SegTree
): Supports any associative operation (monoid) with O(log n) point updates and range queries - Generic Lazy Segment Tree (
LazySegTree
): Supports range updates and range queries in O(log n) time with lazy propagation - Type-safe design: Uses the type system to ensure correctness and prevent misuse
- Comprehensive helper types: Pre-built implementations for common operations (sum, min, max)
- Zero-cost abstractions: Generic design with no runtime overhead
- Well-tested: Extensive test coverage including edge cases
Quick Start
Add this to your Cargo.toml
:
[]
= "0.1.0"
Basic Usage
Segment Tree for Range Sum Queries
use ;
// Define a spec for sum operations
;
Using Helper Types
For common operations, you can use the provided helper types:
use ;
Lazy Segment Tree for Range Updates
use ;
// Define a spec for range add + range sum
;
Using Lazy Segment Tree Helpers
use ;
Advanced Usage
Custom Data Types
You can use segment trees with any type that implements the required traits:
use ;
;
API Reference
SegTree
SegTree::new(size: usize)
- Create empty tree with given sizeSegTree::from_vec(values: &[T])
- Build tree from initial valuesquery(&self, left: usize, right: usize) -> T
- Query range [left, right)update(&mut self, index: usize, value: T)
- Update single element
LazySegTree
LazySegTree::new(size: usize)
- Create empty lazy treeLazySegTree::from_vec(values: &[T])
- Build from initial valuesquery(&self, left: usize, right: usize) -> T
- Query range [left, right)update(&mut self, left: usize, right: usize, value: U)
- Update range [left, right)
Helper Types
Regular Segment Trees:
SegTreeSum<T>
- Range sum queriesSegTreeMin<T>
- Range minimum queriesSegTreeMax<T>
- Range maximum queries
Lazy Segment Trees:
LazySegTreeAddSum<T>
- Range add updates, range sum queriesLazySegTreeAddMax<T>
- Range add updates, range max queriesLazySegTreeAddMin<T>
- Range add updates, range min queriesLazySegTreeReplaceSum<T>
- Range assignment (replace) updates, range sum queries
Performance
All operations have the following time complexities:
- Construction: O(n) for
from_vec
, O(n) fornew
- Point update (SegTree): O(log n)
- Range query: O(log n)
- Range update (LazySegTree): O(log n)
Space complexity: O(n)
Requirements
- Rust 2021 edition or later
- For numeric types:
num-traits
crate features - For min/max operations:
min_max_traits
crate features
License
This project is licensed under the MIT License. See the LICENSE file for details.