Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Created May 21, 2021 20:57
Show Gist options
  • Save misterpoloy/85452187d3c1087c6747aa61aadd2fbd to your computer and use it in GitHub Desktop.
Save misterpoloy/85452187d3c1087c6747aa61aadd2fbd to your computer and use it in GitHub Desktop.
Function to detect 2 anagrams - Frequency counter method
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