Login

Check if Two Strings are Anagrams

Write a function that checks if two strings are anagrams

Advanced


Instructions

Write a function that checks if two strings are anagrams. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

For example, the strings 'aabbcc' and 'ccbbaa' are anagrams. The function should return true if the strings are anagrams and false otherwise.

The function should have the following signature:

const areAnagrams = (str1, str2) => {...}

The function should return a boolean value.

For example, areAnagrams('aabbcc', 'ccbbaa') should return true.

Tests
0/5
Function Call:
Expected:
areAnagrams('aabbcc', 'ccbbaa')
true
Run test

areAnagrams('banana', 'orange')
false
Run test

Hidden Test
?
Run test

Hidden Test
?
Run test

Hidden Test
?
Run test

See Solution

Example

const areAnagrams = (str1, str2) => {
      return str1.split('').sort().join('') === str2.split('').sort().join('');
}

Explanation

The function areAnagrams takes two strings as arguments and returns a boolean value. The function first splits the strings into an array of characters, then sorts the array and joins the characters back into a string. The function then compares the two strings and returns true if they are equal and false if they are not.

Complexity Analysis

The time complexity for this solution is O(nlogn) because of the sorting operation.

Alternative

For loop

const areAnagrams = (str1, str2) => {
      if (str1.length !== str2.length) return false;
      const str1Map = {};
      const str2Map = {};
      for (let i = 0; i < str1.length; i++) {
         str1Map[str1[i]] = (str1Map[str1[i]] || 0) + 1;
         str2Map[str2[i]] = (str2Map[str2[i]] || 0) + 1;
      }
      for (let key in str1Map) {
         if (str1Map[key] !== str2Map[key]) return false;
      }
      return true;
   }
Any improvement idea? Share with us!