Skip to content

Instantly share code, notes, and snippets.

@GreggSetzer
Last active March 8, 2020 15:22
Show Gist options
  • Save GreggSetzer/f1c0fe93b515a2c7f2bd54b4e00b97af to your computer and use it in GitHub Desktop.
Save GreggSetzer/f1c0fe93b515a2c7f2bd54b4e00b97af to your computer and use it in GitHub Desktop.
Javascript Interview Question: Anagram
/*
Check to see if two strings are anagrams, where both strings have the same characters in the same quantity.
Only consider characters, not spaces and punctuation. Consider the strings as case insensitive, where capital
letters are the same as lowercase letters.
*/
function anagram(str1, str2) {
//Step 1: Create a data store for each string.
const charMap1 = getCharMap(str1);
const charMap2 = getCharMap(str2);
const keysArr1 = Object.keys(charMap1);
const keysArr2 = Object.keys(charMap2);
//If the key arrays have different lengths, this is not an anagram.
if (keysArr1.length !== keysArr2.length) {
return false;
}
/*
At this point, there are the same number of characters in each string.
Are they an anagram? We'll use Array.every() helper to determine
if these two strings are anagrams. Thanks to the Array.every() helper,
we can immediately return false if any callback returns false.
*/
return keysArr1.every((char) => charMap1[char] === charMap2[char]);
}
function getCharMap(str) {
let ds = {};
for (let char of str.replace(/[^\w]/g, '').toLowerCase()) {
ds[char] = ds[char] + 1 || 1;
}
return ds;
}
console.log(anagram('aba', 'aab')); //true
console.log(anagram('aba', 'abc')); //false
console.log(anagram('aba', 'abcd')); //false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment