HashSet Basics
Easy
+2 pts
Collections
5/5
In Python, sets provide unique collections with fast membership testing:
tags = {"rust", "python", "coding"}
tags.add("rust") # no duplicate
print("rust" in tags) # O(1) lookup
a = {1, 2, 3}
b = {2, 3, 4}
print(a & b) # intersection: {2, 3}
print(a | b) # union: {1, 2, 3, 4}
print(a - b) # difference: {1}
Rust's HashSet<T> works the same way.
Creating and using HashSet
use std::collections::HashSet;
let mut tags: HashSet<String> = HashSet::new();
tags.insert("rust".to_string());
tags.insert("rust".to_string()); // ignored - already exists
assert_eq!(tags.len(), 1);
if tags.contains("rust") {
println!("Found it!");
}
Set operations
let a: HashSet<i32> = [1, 2, 3].into_iter().collect();
let b: HashSet<i32> = [2, 3, 4].into_iter().collect();
let intersection: HashSet<_> = a.intersection(&b).copied().collect();
let union: HashSet<_> = a.union(&b).copied().collect();
let difference: HashSet<_> = a.difference(&b).copied().collect();
From iterator
let numbers = vec![1, 2, 2, 3, 3, 3];
let unique: HashSet<i32> = numbers.into_iter().collect();
assert_eq!(unique.len(), 3);
Login to see the full task and start coding.
Topics
This is a premium exercise
Log in to unlock the full exercise and start coding.
Login to access this exercise