Skip to content

Instantly share code, notes, and snippets.

@IAMIronmanSam
Last active March 27, 2019 06:38
Show Gist options
  • Save IAMIronmanSam/b689bc2488512e6bfee48d31367fd178 to your computer and use it in GitHub Desktop.
Save IAMIronmanSam/b689bc2488512e6bfee48d31367fd178 to your computer and use it in GitHub Desktop.
Check given word is Anagram or not
function validAnagram(first, second) {
if (first.length !== second.length) {
return false;
}
const lookup = {};
for (let letter of first) {
// if letter exists, increment, otherwise set to 1
lookup[letter] ? lookup[letter] += 1 : lookup[letter] = 1;
}
console.log(lookup)
for (let letter of second) {
// 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', 'nagarams')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment