Rs
Module 4Sets: HashSet & BTreeSetLesson 11 of 2318 min

BTreeSet Ordered Uniques

Sorted unique keys; first/last; range queries mindset.

BTreeSet

rust
use std::collections::BTreeSet;

fn main() {
    let mut s = BTreeSet::new();
    s.insert(5);
    s.insert(1);
    s.insert(3);
    print!("sorted:");
    for x in &s {
        print!(" {x}");
    }
    println!();
    println!("min={:?} max={:?}", s.iter().next(), s.iter().next_back());
}
Output
sorted: 1 3 5
min=Some(1) max=Some(5)

first / last

rust
s.iter().next();      // min
s.iter().next_back(); // max

When to pick BTreeSet vs HashSet

Need Use
------ -----
Fast membership only HashSet
Sorted order / min-max BTreeSet
Order stats lite BTreeSet
Challenge

Given a stream of ints, print median of uniques so far using two structures or BTreeSet (hard mode: just print min/max gap).

Tips
  • Sorted iteration
  • next_back for max
  • Log n ops

Try it live

BTreeSet Ordered UniquesRust 2021
Loading editor…
Output
Press Run to compile and execute.