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);
Your Task
unique_items(items: Vec<i32>) -> Vec<i32>— return unique items (preserve order of first occurrence)common_elements(a: &[i32], b: &[i32]) -> Vec<i32>— find elements in both (sorted output)is_subset(subset: &[i32], superset: &[i32]) -> bool— check if all elements of subset are in superset
…
Login to see the full exercise.
Topics