Algorithms and Data Structures Part VI

Brian Butterly
3 min readMar 21, 2021

Anagrams

Photo by Raphael Schaller on Unsplash

Okay so in this problem we’re asked to check and see if two provided strings are anagrams of each other. One string is an anagram of another if it uses the same characters in the same quantity. We’re also asked to only consider the characters, not spaces or punctuation and to consider capital letters to be the same as lower case.

E.g. anagrams(‘rail safety’, ‘fairy tales’) → True || anagrams(‘RAIL SAFETY’, ‘fairy tales’) → TRUE

So here we have our function. We need to build a character map of string A and one for string B then we will compare the two together.

So first we will write a helper function to build our character map for us.

function buildCharMap(str) {
}

Inside here we will create an empty object that will be our character map then we will iterate through our string and for every character inside there we will add it to our charMap.

function buildCharMap(str) {
const charMap = {}
}

Then we will add a for loop like so…

here we do the replace and lower case logic in the for loop. We are also using the regular expression of /[^\w]/g to remove spaces and exclamation marks from the string and replacing it with an empty string “”. Now that it’s all cleaned up we change it to lower case .toLowerCase().

We then take our charMap, assign a key to it and then increment the value at that character. Then don’t forget to return charMap.

We can now use this helper to build a character map for string a and string b.

On line 12 and 13 you can see we created variables with the helper function we just created to build out our charMaps for each string. Now it’s up to us to compare the two.

Object.keys() will pull out the keys inside an object and we use this to compare each string. .length with tell us how many keys in each object.

So we take the number of keys in aCharMap and compare them to bCharMap

If they don't match then we don’t have an anagram so we want to return false. If they do have the same characters then we can proceed. So we iterate over aCharMap’s characters and if it they’re not equal to bCharMap’s characters then return false because we don’t have an anagram.

Finally, if we succeed in both of these checks then we must have an anagram so we just return true.

So here is our entire solution.

--

--