Ad

Write a function that takes two strings as arguments and returns true if they are anagrams of each other, and false otherwise. 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 "iceman" and "cinema" are anagrams of each other.

Function Signature: function isAnagram(str1, str2)

Input:

Two strings str1 and str2 of length n (1 ≤ n ≤ 10^3) containing only lowercase letters.
Output:

A boolean value true if the two input strings are anagrams of each other, and false otherwise.
Example:

isAnagram('listen', 'silent'); // true
isAnagram('race', 'care'); // true
isAnagram('night', 'thing'); // false

function isAnagram(str1, str2) {
  if (str1.length !== str2.length) {
    return false;
  }

  const frequency = {};

  for (let i = 0; i < str1.length; i++) {
    const char = str1[i];
    if (frequency[char]) {
      frequency[char]++;
    } else {
      frequency[char] = 1;
    }
  }

  for (let i = 0; i < str2.length; i++) {
    const char = str2[i];
    if (!frequency[char]) {
      return false;
    } else {
      frequency[char]--;
    }
  }

  return true;
}