Skip to content

Instantly share code, notes, and snippets.

@torressam333
Created December 8, 2022 20:51
Show Gist options
  • Save torressam333/f2454f836058a8baeb16e25010682336 to your computer and use it in GitHub Desktop.
Save torressam333/f2454f836058a8baeb16e25010682336 to your computer and use it in GitHub Desktop.
Simple Version of Valid Anagram O(n) Time Complexity
/* Simple b/c it doesn't account for spaces, special chars etc...*/
const validAnagram = (str1, str2) => {
// Immediately return if strings are diff length
if (str1.length !== str2.length) return false;
// Create "bank" for letters to live in
let chars = {};
// Loop over first string and add letters to chars
for (let letter of str1) {
// Add in each letter to the store of chars
chars[letter] = (chars[letter] || 0) + 1;
}
// Loop over 2nd string
for (let letter of str2) {
// No matching letter -> falsy
if (!chars[letter]) return false;
// Matching letter gets reduced by one
else chars[letter] -= 1;
}
// No falsy returns then it is a valid anagram
return true;
};
// Simple Test Cases
console.log(validAnagram("", ""));
console.log(validAnagram("aaz", "zza"));
console.log(validAnagram("anagram", "nagaram"));
console.log(validAnagram("rat", "car"));
console.log(validAnagram("awesome", "awesom"));
console.log(validAnagram("qwerty", "qeywrt"));
console.log(validAnagram("texttwisttime", "timetwisttext"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment