How to solve the anagram algorithm question!

ham_codes
2 min readMar 14, 2021

--

Lately I’ve been continuing my path to learn data structures and algorithms. One of the questions I faced recently was how to tell if given two strings, they were anagrams. An anagram is a word or phrase that’s formed by rearranging the letters of another word or phrase. So basically an anagram could be “dormitory” which can be turned into “dirty room”. At first my head was going in a bunch of different directions in respect to how to solve this problem. After some consideration, I think the best solution is below. Here are the steps:

The first thing I will do is create a function that takes each string I’m being given and strip it down to get rid of all the spaces, punctuation, and make everything lowercase. In order to do this, I’m going to have to use regex. What is regex? Regex stands for regular expression. According to the MDN documentation, “Regular expressions are patterns used to match character combinations in strings.” We will have to use regex in this case to be able to ignore all the punctuation and only focus on the letters in each string. I will do this by creating a function that not only uses regex, but four other methods within that will make my string look the way I want it to. Within this function I will use toLowerCase, split, sort, and join. When all of these are used on the string, I will get back a string that has no punctuation, no capital letters, the string sorted alphabetically, and then joined back together. Here is the function I will use to make this happen:

Now that my string is broken down the way I need it, I can simply compare the two strings that are passed in as arguments. This way, it will look at both strings, figure out if there are the same amount of letters and if they are the same. This is easy now because the strings were alphabetically sorted and all of the spaces and punctuation are removed. Here is the function that will look at both strings and determine if they are equal and the helper function we created earlier together:

The biggest problem I had was looking into regex and trying to remember the syntax for this. Below are some links to the methods I used to break the string down. Hope you enjoyed reading!

Regex:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

toLowerCase:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase

Split:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

Sort:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Join:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

--

--

No responses yet