Next Challenge: Anagram

Tyler Hueter
5 min readOct 12, 2019

#3 in the technical interview series looks at the common anagram challenge.

Challenge: Create a function that accepts 2 arguments and returns true if they are anagrams of each other.

First, what is an anagram? Dictionary.com defines an anagram as

noun; a word, phrase, or sentence formed from another by rearranging its letters:“Angel” is an anagram of “glean.”

So, what does that mean for us? It means we have to see if we can rearrange all the characters from input1 and see if we can match input2. We are going to look at 2 different solutions to this challenge. The one give that we have is that both inputs will be strings that will contain actual words or phrases. It is important to note, as with any issue in coding, there can be many different ways to solve a problem. We are just going to look at two of them.

#1 Objective Comparison

The first solution we are going to look at will entail comparing two objects. But we only have strings, right? To make this solution work we will need to write two functions. The first will take our input string, sanitize it a bit, and then use it to create an object.

There is a lot to unpack here so we will take it slow. First, we use an object literal {} to define our obj variable. Next, we use a for…in statement. A for…in statement iterates over an object for each specific variable. Let’s look at the line ( for (let i in str) ) a little bit closer because this is a little tricky.

Here is the MDN javascript docs description of a for…in statement: The for...in statement iterates a specified variable over all the enumerable properties of an object. For each distinct property, JavaScript executes the specified statements.

Now this gets a little more complicated when you consider this statement defines that specific variable as the key in a key:value pair. If we pass in the object { name: ‘buddy’, animal: ‘dog’, breed: ‘boxer’} the specific variables selected in the for…in statement would be name, animal, and breed. So when we pass in a string (as we have above, str) the for…in statement uses the index position as the ‘key’. This means when we pass in the string ‘cat’, the specific variables would be 0,1,2. Still with me?

Ok, in the next line (7), we do a little sanitation. Sanitation or to sanitize data is to transform it to a comparable level. This involves methods like making all letters the same case, or maybe to remove extra spaces. If all the data is transformed in the same way then we can make a true comparison. So back to line 7. We define the variable letter as the value of the character located at index position i, and we then transform it to lower case. Next, we apply an if statement to test our object we defined in the beginning, obj. We say, if our object(obj) contains the key letter then increment its value by 1, if not then add a key:value pair of letter: 1 to the object.

Whew, that is a lot of words but our end result makes the comparison possible. If we call our newObj function and pass it the string “married”, we will get back an object that looks like { m:1, a:1, r:2, i:1, e:1, d:1 }. Each letter is now a key and its value is the number of times it appears in our original string. Now let’s compare some strings.

We have a couple different things going on here. First, we call our newObj() function to convert the initial strings passed in and set them to a variable, a and b respectively. Next, we run a quick test. The Object.keys() is a built in function that will return an array of the keys from the object that is passed in. Then we apply the length method to each array and if they are not the same length, the two strings cannot be anagrams.

Finally we bring back the for…in statement. This time we are using the specific variable (item) to compare each key:value pair from both objects. If they are not equal then the strings cannot be anagrams. If the two objects contain the exact same key:value pairs then the two strings are anagrams and we return true. Done!

#2 Chain Gang

In this second solution we are going to return to several of the methods that should become familiar to you by now (if you are following this series, 1 and 2) such as .split()and .join(). We are going to add some new ones in the mix as well. Let’s get started.

Like the solution above we are going to write a helper function so that we can keep our code a little cleaner. Again we are going to employ the ability to chain methods and while it looks a little crazy we will go over it all quickly. Here is what our helper function looks like:

That’s a long chain!

Here we are applying five consecutive methods to our input string. Starting out we use .toLowerCase() just to make sure that all characters are of the same case. Next we call .replace() and inside of that we use some RegEx as the argument. RegEx is a much bigger topic and one for a future post, but in the meantime you can see the MDN docs HERE. By using RegEx and the .replace() method, any spaces, punctuation or unwanted characters are removed and replaced with an empty string.

So far we have taken our string, made all the letters lower case, and removed any extra spaces or unwanted characters. Now we will call .split() to convert the string to an array. Then .sort() to arrange each character in order a-z. And finally .join() to return the array to a string. Now if we apply this helper function we can just compare the two strings directly!

Much cleaner!

Annnd done! There you go, two different solutions to the Anagram Challenge. This is a very common challenge, and again there are always many different ways to solve problems. Good luck out there and happy hacking!

--

--