(function(){
var hashMap = {};
function isAnagram (str1, str2) {
if(str1.length !== str2.length){
return false;
}
// Create hash map of str1 character and increase value one (+1).
createStr1HashMap(str1);
// Check str2 character are key in hash map and decrease value by one(-1);
var valueExist = createStr2HashMap(str2);
// Check all value of hashMap keys are zero, so it will be anagram.
return isStringsAnagram(valueExist);
}
function createStr1HashMap (str1) {
[].map.call(str1, function(value, index, array){
hashMap[value] = value in hashMap ? (hashMap[value] + 1) : 1;
return value;
});
}
function createStr2HashMap (str2) {
var valueExist = [].every.call(str2, function(value, index, array){
if(value in hashMap) {
hashMap[value] = hashMap[value] - 1;
}
return value in hashMap;
});
return valueExist;
}
function isStringsAnagram (valueExist) {
if(!valueExist) {
return valueExist;
} else {
var isAnagram;
for(var i in hashMap) {
if(hashMap[i] !== 0) {
isAnagram = false;
break;
} else {
isAnagram = true;
}
}
return isAnagram;
}
}
isAnagram('stackoverflow', 'flowerovstack'); // true
isAnagram('stackoverflow', 'flowervvstack'); // false
})();
Time complexity :- 3n i.e O(n).