Software Interview Question: Test if two strings are an Anagram of each other

I was asked this question during a whiteboarding session while interview for a software engineering job:

Test if two strings are an anagram of each other.

What is an anagram?

I didn’t know what anagram meant, so I asked the interviewer to define it for me.

An anagram is where two strings have the same frequency of letters in them. For example “abc” and bac” are anagrams of each other. But “abc” and “aabc” are not because the former has one “a” and the latter has two.

Anyhow, I was able to answer the question and I think this contributed to me landing the job offer.

And I can say for sure if you don’t know something that you think might be important to solving whatever problem you are faced with (even when on the spot), don’t feel afraid to speak up and ask questions. A hiring manager wants to see you interacting and how you think.

Here is a video of me coding and explaining the solution.

Here is the code from the above video with slight modification to test the positive and negative case:

/**
 * Anagram example: "emike", "eemik"
 * 
 * This function will return true if the two strings have the same frquency of letters
 */

function isAnagram($string1, $string2) {

    if(strlen($string1) != strlen($string2)) return false;

    $a1 = [];
    $a2 = [];

    // count letter frquency of string1
    foreach(str_split($string1) as $key => $value) {
        if(!isset($a1[$value])) $a1[$value] = 0;
        $a1[$value]++;
    }

    // count letter frquency of string1
    foreach(str_split($string2) as $key => $value) {
        if(!isset($a2[$value])) $a2[$value] = 0;
        $a2[$value]++;
    }

    // compare the letter frquency between the two strings
    foreach($a1 as $key => $value) {
        if(!isset($a2[$key])) return false;
        if($a1[$key] != $a2[$key]) return false;
    }

    return true;
}

if(isAnagram("kmgke", "emikk")) print "is anagram\n"; else print "not anagram\n";
if(isAnagram("emike", "eemik")) print "is anagram\n"; else print "not anagram\n";

Then the output looks like this:

not anagram
is anagram

And by the way, I’ve since learned the count_chars PHP function performs the anagram test a little faster than the above solution and with only a single line of code (line 2).

function isAnagram3($string1, $string2) {
    return(count_chars($string1, 1) == count_chars($string2, 1));
}