HashMap<K, V> stores key-value pairs with O(1) average lookup time.
use std::collections::HashMap;
let mut scores = HashMap::new();
scores.insert("Alice", 100);
scores.insert("Bob", 80);// Returns Option<&V>
if let Some(score) = scores.get("Alice") {
println!("Alice: {}", score);
}
// Or with default
let score = scores.get("Charlie").unwrap_or(&0);Powerful pattern for conditional insertion:
// Insert only if key doesn't exist
scores.entry("Alice").or_insert(50);
// Modify existing or insert
let count = scores.entry("Alice").or_insert(0);
*count += 1;The Entry API is perfect for counting frequencies - a common interview pattern!
for (key, value) in &scores {
println!("{}: {}", key, value);
}Implement char_frequency(s) that counts character occurrences.
HashMap<char, u32>"Hello" → {h: 1, e: 1, l: 2, o: 1}use std::collections::HashMap;
fn char_frequency(s: &str) -> HashMap<char, u32> {
let mut freq = HashMap::new();
for c in s.chars() {
if c.is_alphabetic() {
let c = c.to_ascii_lowercase();
*freq.entry(c).or_insert(0) += 1;
}
}
freq
}