Check whether two strings are anagram of each other

Please follow & like us :)

Coding Interview Question

Write a function to check whether two given strings are anagram of each other or not.

Clarification:

An anagram of a string is another string that contains the same characters, only the order of characters can be different.

Sample Data:

Example 1:

Input:  string1 => “abcd” and string2 =>  “dabc” 
Output: true

Example 2:

Input: string1 =>'amp' and string2 =>'map'
Output: true

Example 2:

Input: string1 =>'axp' and string2 =>'map'
Output: false

To solve this problem, we can sort both strings and can compare each character on both strings. But using sort would be expensive execution.

To make performance better we can use Has Map which will hold key/val pairs. We can easily check if key doesn’t exist in map then we can return false and don’t have to scan string till last character.

Step1: We will create Has map and using for loop for string 1 we will add all characters as key in map.

Step2: We will use for loop and check if all characters from string 2 exist in map and if that is true we will return true otherwise we will return false.

Putting logic into actual working code now.

const anagramCheck = (str1, str2) => {
  let str1Count = {};
  let str2Count = {};
  for (let i = 0; i < str1.length; i++) {
    str1Count[str1[i]] = (str1Count[str1[i]] || 0) + 1;
  }
  for (let j = 0; j < str2.length; j++) {
    if (!str1Count[str2[j]]) {
      return false;
    }
    else {
      str1Count[str2[j]] -= 1;
    }
  }
  return true;
}
console.log(anagramCheck('amp','map'));

Test it Out here on Code Playground: