Anagram
May 3, 2021
Let’s talk about a common question you will likely see on a technical interview. An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, the word anagram itself can be rearranged into nag a ram, also the word binary into brainy and the word adobe into abode.
function validAnagram(str1, str2){
if (str1.length !== str2.length){
return false;
}
var obj1 = {};
var obj2 = {};
for(let char of str1){
obj1[char] = (obj1[char] || 0) + 1;
}
for(let char of str2){
obj2[char] = (obj2[char] || 0) + 1;
}
for(let val in obj1){
if(obj2[val] !== obj1[val]){
return false;
}
}
return true;
}