Ad

Most efficient version I could come up with.
Uses an array instead of an object and only uses one loop with fewer operations.

Code
Diff
  • function isAnagram(str1, str2) {
      if (str1.length !== str2.length) {
        return false;
      }
    
      const charCount = new Array(26).fill(0);
    
      for (let i = 0; i < str1.length; i++) {
        charCount[str1.charCodeAt(i) - 97]++;
        charCount[str2.charCodeAt(i) - 97]--;
      }
    
      for (let count of charCount) {
        if (count !== 0) {
          return false;
        }
      }
    
      return true;
    }
    • function isAnagram(str1, str2) {
    • if (str1.length !== str2.length) {
    • return false;
    • }
    • const frequency = {};
    • const charCount = new Array(26).fill(0);
    • for (let i = 0; i < str1.length; i++) {
    • const char = str1[i];
    • if (frequency[char]) {
    • frequency[char]++;
    • } else {
    • frequency[char] = 1;
    • }
    • charCount[str1.charCodeAt(i) - 97]++;
    • charCount[str2.charCodeAt(i) - 97]--;
    • }
    • for (let i = 0; i < str2.length; i++) {
    • const char = str2[i];
    • if (!frequency[char]) {
    • for (let count of charCount) {
    • if (count !== 0) {
    • return false;
    • } else {
    • frequency[char]--;
    • }
    • }
    • return true;
    • }