Created
May 21, 2021 20:57
-
-
Save misterpoloy/85452187d3c1087c6747aa61aadd2fbd to your computer and use it in GitHub Desktop.
Function to detect 2 anagrams - Frequency counter method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function validAnagram(strA, strB){ | |
if (strA.length !== strB.length) return false; | |
const strAcounter = {}; | |
for (const char of strA) { | |
strAcounter[char] = (strAcounter[char] || 0) + 1; | |
} | |
const strBcounter = {}; | |
for (const char of strB) { | |
strBcounter[char] = (strBcounter[char] || 0) + 1; | |
} | |
const counter = Object.keys(strAcounter); | |
for (const key of counter) { | |
if (key in strBcounter) { | |
if (strAcounter[key] !== strBcounter[key]) { | |
return false; | |
} | |
} else { | |
return false; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment