Skip to content

Instantly share code, notes, and snippets.

@premrajah
Last active March 3, 2020 00:00
Show Gist options
  • Save premrajah/b3f400c87873f0cad2c6c080a3099756 to your computer and use it in GitHub Desktop.
Save premrajah/b3f400c87873f0cad2c6c080a3099756 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 or 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];
// cant find letter or letter is zero then its not a anagram
if(!lookup[letter]) {
return false;
} else {
lookup[letter] -= 1;
}
}
return true;
}
console.log(ValidAnagram("card", "darc"));
console.log(ValidAnagram("card", "larc"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment