DEV Community

Cover image for JS Coding Question #6: Is Anagram
Let's Code
Let's Code

Posted on • Updated on

JS Coding Question #6: Is Anagram

Interview Question #6:

Write a function that will check if two strings are anagram❓🤔

If you need practice, try to solve this on your own. I have included 2 potential solutions below.

Note: There are many other potential solutions to this problem.

Feel free to bookmark 🔖 even if you don't need this for now. You may need to refresh/review down the road when it is time for you to look for a new role.

Code if you want to play around with it: https://codepen.io/angelo_jin/pen/xxrVmdg

Solution #1: Array Sort

  • This solution will utilize a helper function to remove all unwanted punctuation and symbols, basically non-alphabetic characters. Then, will sort the string. Once both strings are sorted, compare if they are equal
function isAnagram(stringA, stringB) {
    const normalize = (str) => {
        return str
            .replace(/[^\w]/g, '')
            .toLowerCase()
            .split('')
            .sort()
            .join('')
    }

  return normalize(stringA) === normalize(stringB);
}
Enter fullscreen mode Exit fullscreen mode

Solution #2: Object/Hash Map

  • This solution is what I prefer although more steps are needed than the first solution.

Create a helper function to build a hash map for the string counting each and every characters. Once map is built, iterate and compare the count of first map against the second map.

function createCharMap (str) {
    const map = {}
    const normalizedString = str.replace(/[^\w]/g, '').toLowerCase()

    for (let char of normalizedString) {
        map[char] = map[char] + 1 || 1
    }

    return map
}

function isAnagram(stringA, stringB) {
  const charMapA = createCharMap(stringA)
  const charMapB = createCharMap(stringB)

  if (Object.keys(charMapA).length !== Object.keys(charMapB).length) {
    return false
  }

  for (let char in charMapA) {
    if (charMapA[char] !== charMapB[char]) {
      return false
    }
  }

  return true
}
Enter fullscreen mode Exit fullscreen mode

Happy coding and good luck if you are interviewing!

If you want to support me - Buy Me A Coffee

In case you like a video instead of bunch of code 👍😊

Top comments (1)

Collapse
 
frontendengineer profile image
Let's Code

that would work too, very optimized version. Thanks much.