JS Coding Question #6: Is Anagram

frontendengineer

Let's Code

Posted on September 4, 2021

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 ๐Ÿ‘๐Ÿ˜Š

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
frontendengineer
Let's Code

Posted on September 4, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About