Rs
Module 4HashMap: Add, Get, RemoveLesson 9 of 2322 min

Frequency Maps (classic)

Count characters/words; two-sum with HashMap; anagram check.

Frequency map

rust
use std::collections::HashMap;

fn main() {
    let s = "banana";
    let mut freq: HashMap<char, i32> = HashMap::new();
    for ch in s.chars() {
        *freq.entry(ch).or_insert(0) += 1;
    }
    let mut keys: Vec<_> = freq.keys().copied().collect();
    keys.sort();
    for k in keys {
        println!("{k}: {}", freq[&k]);
    }
}
Output
a: 3
b: 1
n: 2

Two Sum pattern

For each x, need target - x already seen → store value -> index.

Anagram

Count chars in s; decrement with t; all zeros (or second map equal).

Rust char notes

chars() is Unicode scalars — fine for interviews unless bytes specified.

Challenge

fn is_anagram(a: &str, b: &str) -> bool using one HashMap.

Tips
  • entry for counts
  • Store index in map for two-sum
  • One pass O(n)

Try it live

Frequency Maps (classic)Rust 2021
Loading editor…
Output
Press Run to compile and execute.