#segment #sum #query #interval #fenwick

segment-tree

Quickly perform interval queries or modifications

3 stable releases

2.0.0 Dec 28, 2018
1.1.0 Aug 26, 2017
1.0.0 Aug 26, 2017

#599 in Data structures

Download history 656/week @ 2023-10-29 593/week @ 2023-11-05 556/week @ 2023-11-12 748/week @ 2023-11-19 656/week @ 2023-11-26 597/week @ 2023-12-03 675/week @ 2023-12-10 426/week @ 2023-12-17 231/week @ 2023-12-24 268/week @ 2023-12-31 515/week @ 2024-01-07 451/week @ 2024-01-14 474/week @ 2024-01-21 456/week @ 2024-01-28 446/week @ 2024-02-04 1002/week @ 2024-02-11

2,387 downloads per month
Used in 8 crates (2 directly)

MIT license

72KB
1.5K SLoC

segment-tree

This crate contains various data structures useful for quickly performing interval queries or modifications in some array.

The data structures in this crate are all trees. The trees are represented using an array for high performance and low memory usage. Despite the name of the crate, not every tree in this crate is a segment tree.

Cargo.toml

[dependencies]
segment-tree = "2"

Example

The example below shows a segment tree, which allows queries to any interval in logaritmic time.

use segment_tree::SegmentPoint;
use segment_tree::ops::Min;

let array = vec![4, 3, 2, 1, 2, 3, 4];
let mut tree = SegmentPoint::build(array, Min);

// Compute the minimum of the whole array.
assert_eq!(tree.query(0, tree.len()), 1);

// Compute the minimum of part of the array.
assert_eq!(tree.query(0, 3), 2);

// Change the 1 into a 10.
tree.modify(3, 10);

// The minimum of the whole array is now 2.
assert_eq!(tree.query(0, tree.len()), 2);

This crate also has a PointSegment type, which instead allows modifications to intervals.

The related crate prefix_sum might also be of interest.

Dependencies

~105KB