Skip to content

Instantly share code, notes, and snippets.

@emersxw
Created July 12, 2020 16:16
Show Gist options
  • Save emersxw/b8089107a8e5d3ecefec0ddf2791a2f4 to your computer and use it in GitHub Desktop.
Save emersxw/b8089107a8e5d3ecefec0ddf2791a2f4 to your computer and use it in GitHub Desktop.
function validAnagram(first, second) {
if (first.length !== second.length) {
return false;
}
const lookup = {};
for (let i = 0; i < first.length; i++) {
let letter = first[i];
// if letter exists, increment, otherwise set to 1
lookup[letter] ? lookup[letter] += 1 : lookup[letter] = 1;
}
console.log(lookup)
for (let i = 0; i < second.length; i++) {
let letter = second[i];
// can't find letter or letter is zero then it's not an anagram
if (!lookup[letter]) {
return false;
} else {
lookup[letter] -= 1;
}
}
return true;
}
// {a: 0, n: 0, g: 0, r: 0, m: 0,s:1}
validAnagram('anagrams', 'nagaramm')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment