Segment Tree Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Segment Tree runs in O(log n) time and O(n) space, in Rust as in every other language.
- ✓Vec<T> for storage and the standard numeric traits for the merge; there is no segment tree in std.
- ✓Take the merge as a closure or a generic F: Fn(&T, &T) -> T stored in the struct, and require T: Clone.
- ✓The Rust trap: Integer overflow behaves DIFFERENTLY between build profiles. In a debug build an overflowing add panics with "attempt to add with overflow"; in a release build the same code wraps silently by default.
- ✓A Vec<i64> is contiguous and the query loop is branch-predictable, so this is one of the faster implementations of the eight with no tuning at all.
What Segment Tree actually is
Segment Tree in Rust: what you actually reach for
Rust implementation
pub struct SegmentTree<T, F> {
n: usize,
tree: Vec<T>,
merge: F,
identity: T,
}
impl<T: Clone, F: Fn(&T, &T) -> T> SegmentTree<T, F> {
pub fn new(data: &[T], merge: F, identity: T) -> Self {
let n = data.len();
let mut tree = vec![identity.clone(); 2 * n];
tree[n..].clone_from_slice(data);
for i in (1..n).rev() {
tree[i] = merge(&tree[2 * i], &tree[2 * i + 1]);
}
Self { n, tree, merge, identity }
}
pub fn update(&mut self, index: usize, value: T) {
let mut i = index + self.n;
self.tree[i] = value;
while i > 1 {
i /= 2;
self.tree[i] = (self.merge)(&self.tree[2 * i], &self.tree[2 * i + 1]);
}
}
/// Merge of [left, right).
pub fn query(&self, left: usize, right: usize) -> T {
let (mut lo, mut hi) = (left + self.n, right + self.n);
let mut acc = self.identity.clone();
while lo < hi {
if lo % 2 == 1 {
acc = (self.merge)(&acc, &self.tree[lo]);
lo += 1;
}
if hi % 2 == 1 {
hi -= 1;
acc = (self.merge)(&acc, &self.tree[hi]);
}
lo /= 2;
hi /= 2;
}
acc
}
}
// Sums: use i64, and remember debug PANICS on overflow while release WRAPS.
// let tree = SegmentTree::new(&values, |a: &i64, b: &i64| a + b, 0i64);Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Segment Tree?
Vec<T> for storage and the standard numeric traits for the merge; there is no segment tree in std. The type that matters most here is the integer type you choose, because Rust makes overflow behaviour explicit rather than leaving it to chance: i64 for sums, or checked_add when even that could wrap.
What is the most common Rust mistake when implementing Segment Tree?
Integer overflow behaves DIFFERENTLY between build profiles. In a debug build an overflowing add panics with "attempt to add with overflow"; in a release build the same code wraps silently by default. So a sum tree that passes every test under cargo test can return wrong answers in production, and the difference is a compiler flag, not the code. Use i64/i128 for headroom, or checked_add/saturating_add to make the decision explicit.
How does Segment Tree actually perform in Rust?
A Vec<i64> is contiguous and the query loop is branch-predictable, so this is one of the faster implementations of the eight with no tuning at all. Bounds checking costs a comparison per access; the loop shape below is amenable to the optimiser eliding many of them. Reserve the exact capacity up front, 2n, so the build performs no reallocation. Time complexity is O(log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.