Check to see if the two provided strings are anagrams of each other. One string is an anagram of another if it uses the same characters in the same quantity.
2 min readNov 25, 2022
- Only consider characters, no spaces or punctuation
- Consider capital letters to be the same as lowercase
Examples:
- anagrams(‘rail safety’, ‘fairy tales’) === true
- anagrams(‘RAIL! SAFETY!’, ‘fairy tales’) === true
- anagrams(‘Hi there’, ‘Bye there’) === false
Let’s address this interview question using below two approaches
First Approach
function anagrams(strA,strB){
// this pattern "/[^\w]/g" will remove spcaes and punchuation and convert into an char array using split
const firstArray = strA.replace(/[^\w]/g,"").toLowerCase().split("");
const secondArray = strB.replace(/[^\w]/g,"").toLowerCase().split("");
console.log(firstArray,secondArray);
//creating empty objects
const firstObj = {},scondObj = {};
for(let item of firstArray){
//checking if item already exist
if(firstObj[item]){
//checking if item already exist then only increament its value by one
firstObj[item]++;
}else{
//newly added an item into an object with initializing value to 1
firstObj[item] = 1;
}
}
for(let item of secondArray){
//checking if item already exist
if(scondObj[item]){
//increament its value by one
scondObj[item]++;
}else{
//newly added an item into an object with initializing value to 1
scondObj[item] = 1;
}
}
console.log(firstObj,scondObj);
//provides length of items contained by firstObj
console.log(Object.keys(firstObj).length);
console.log(Object.keys(scondObj).length);
//checking for length of both objects because if not then they are not anagrams straightforward
if(Object.keys(firstObj).length === Object.keys(scondObj).length){
let isAnagram = true;
//looping through the firstObj and checking if any where is there any condition where value of any key from both objects are different with some function
Object.entries(firstObj).some(([key,value])=>{
if(value !== scondObj[key]){
isAnagram = false;
// break the loop by returning true for some function
return true;
}
});
return isAnagram;
}else{
return false;
}
}
console.log(anagrams('rail safety', 'fairy tales'));
Second Approach
function testAnagrams(strA,strB){
//removing spaces and exclamation mark etc ... and converting into lowerCase
const cleanStrA = strA.replace(/[^\w]/g,"").toLowerCase();
const cleanStrB = strB.replace(/[^\w]/g,"").toLowerCase();
//creating array of characters form string
const firstArray = cleanStrA.split("");
const secondArray = cleanStrB.split("");
//sorting the array and again converting it into string with join method and checking if equal or not
if(firstArray.sort().join("") === secondArray.sort().join("")){
return true;
}else{
return false;
}
}
console.log(anagrams('rail safety', 'fairy tales'));
This one is a bit easy and straightforward forward so go with this one if asked in any interview to solve this type of anagram question in javascript.