Skip to content

Instantly share code, notes, and snippets.

@dre4success
Created September 12, 2018 09:44
Show Gist options
  • Save dre4success/3d1f1ce57f5ae1e0d2ff67bd69dd3651 to your computer and use it in GitHub Desktop.
Save dre4success/3d1f1ce57f5ae1e0d2ff67bd69dd3651 to your computer and use it in GitHub Desktop.
Giving two strings, it should return true if it's an anagram i.e a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once
function anagram (str1, str2) {
if (str1.length !== str2.length) return false
let frequencyCounter = {}
for (let val of str1) {
// increment occurence of val in frequencyCounter
frequencyCounter[val] = (frequencyCounter[val] || 0) + 1
}
for (let val of str2) {
if(!frequencyCounter[val]) {
return false
} else {
// decrement the occurence of val
frequencyCounter[val] -= 1
}
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment