Rs
Module 4Sets: HashSet & BTreeSetLesson 10 of 2320 min

HashSet Insert, Contains, Remove

Unique elements, O(1) membership tests.

HashSet

rust
use std::collections::HashSet;

fn main() {
    let mut s = HashSet::new();
    println!("insert 3 first={}", s.insert(3));
    println!("insert 3 again={}", s.insert(3)); // false, already present
    println!("contains 3={}", s.contains(&3));
    println!("remove 3={}", s.remove(&3));
    println!("contains 3 now={}", s.contains(&3));
}
Output
insert 3 first=true
insert 3 again=false
contains 3=true
remove 3=true
contains 3 now=false

From iterators

rust
let set: HashSet<_> = [1,2,2,3].into_iter().collect();

Interview uses

  • Seen numbers (duplicates)
  • Visited nodes in graphs/grids
  • Dictionary word set

Set algebra (methods)

intersection, union, difference — or DIY with contains loops.

Challenge

Return the first duplicate value as Option<i32>.

Tips
  • insert returns bool
  • contains is O(1) avg
  • Visited set for graphs

Try it live

HashSet Insert, Contains, RemoveRust 2021
Loading editor…
Output
Press Run to compile and execute.