Rust Interview Puzzles: Check if 2 strings are Anagrams

Rust Interview Puzzles: Check if 2 strings are Anagrams

Problem

We need to check whether 2 provided strings s1 and s2 are Anagrams. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase. For this puzzle we could assume that we work only with ASCII characters, there is no distinction between lower and upper case letters, and that we can ignore spaces in the strings.

Examples:

Input s1Input s2Output
"New York Times""monkeys write"true
"McDonald's restaurants""Uncle Sam's standard rot"true
"coronavirus""carnivorous"true
"Daddy""Mummy"false

Solution

fn check_if_anagram_strings(s1: &str, s2: &str) -> bool {
    let mut map1 = HashMap::new();
    let mut map2 = HashMap::new();

    s1.chars()
        .filter(|&c| c != ' ')
        .zip(s2.chars().filter(|&c| c != ' '))
        .for_each(|(char1, char2)| {
            let count1 = map1.entry(char1.to_ascii_lowercase()).or_insert(0);
            *count1 += 1;
            let count2 = map2.entry(char2.to_ascii_lowercase()).or_insert(0);
            *count2 += 1;
        });

    map1 == map2
}

Explanation

One simple way to solve the puzzle in linear time is to use 2 HashMaps. Iterating over the 2 strings s1 and s2 at once (we took s1.chars() iterator and zipped it with s2.chars() iterator) we could count unique letters in each of the strings, saving counts to the respective maps map1 and map2. In the end, if both maps are equal (contain the same letter-count key-value pairs), then it means that both strings contain the same letters an equal number of times. In other words, the strings are anagrams.

Complexity

The time complexity of this solution is O(n) (where n is the size of the input strings). The auxiliary space complexity is O(c) (where c is the size of the alphabet).


Rust Playground with this code