Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

242. Valid Anagram

Check if t is an anagram of s.

HashMap approach:

#![allow(unused)]
fn main() {
// time O(n), space O(n)
pub fn is_anagram(s: String, t: String) -> bool {
    let mut letter_counts: HashMap<char, i32> = HashMap::with_capacity(s.len());
    for s_c in s.chars() {
        letter_counts
            .entry(s_c)
            .and_modify(|v| *v += 1)
            .or_insert(1);
    }

    for t_c in t.chars() {
        letter_counts
            .entry(t_c)
            .and_modify(|v| *v -= 1)
            .or_insert(-1);
    }

    letter_counts.values().all(|&v| v == 0)
}
}

Fixed array approach (ASCII lowercase only, faster, O(1) space):

#![allow(unused)]
fn main() {
pub fn is_anagram_array(s: String, t: String) -> bool {
    let mut letter_counts = [0; 26];
    for s_c in s.chars() {
        letter_counts[(s_c as u8 - b'a') as usize] += 1;
    }

    for t_c in t.chars() {
        letter_counts[(t_c as u8 - b'a') as usize] -= 1;
    }

    letter_counts.iter().all(|&v| v == 0)
}
}