Anagram in Javascript

Jitendra Davariya
2 min readMay 26, 2021

--

Problem Statement: Check whether 2 strings are Anagram

e.g. Example:

  1. If the input is “abc” and “cba”, the output is true
  2. If the input is “aabb” and “bbaa”, the output is true
  3. If the input is “cat” and “atb”, the output is false

Solution

A basic solution where your input string is always in lower characters and no need to check for special characters.

function isAnagram(first, second) {
if(!first || !second || first.length !== second.length) {
return false;
}
else {
let firstLength = 0;
let secondLength = 0;
for(let i=0; i< first.length; i++) {
firstLength += first[i].charCodeAt();
secondLength += second[i].charCodeAt();
}

if(firstLength === secondLength) {
return true;
}

return false;
}
}
// Test Cases
console.log(isAnagram('abc', 'cab'));
console.log(isAnagram('aabb', 'aabb '));
console.log(isAnagram('aabb', 'baba'));

An advanced Anagram that provides validation for alphabetic characters, no matter if there are capital or special characters are available

e.g. Example:

  1. If the input is “Abc” and “bcaa”, the output is false
  2. If the input is “New York Times” and “monkeys write”, the output is true
  3. If the input is “Church of Scientology” and “rich-chosen goofy cult”, the output is true
function isAnagram(first, second) {
if(!first || !second) {
return false;
}
else {
let firstLength = 0;
let secondLength = 0;
const maxLength = first.length > second.length ? first.length : second.length;

for(let i=0; i< maxLength; i++) {
firstLength += getCharCode(first[i]);
secondLength += getCharCode(second[i]);;
}

if(firstLength === secondLength) {
return true;
}

return false;
}
function getCharCode(char) {
if(char) {
const regex = /[a-z]/g;
const newChar = char.toLowerCase();
if(regex.exec(newChar)) {
return newChar.charCodeAt();
}
}
return 0;
}
}
//Test Casesconsole.log(isAnagram('abc', 'cab'));
console.log(isAnagram('aabb', 'bbad'));
console.log(isAnagram('New York Times', 'monkeys write'));
console.log(isAnagram('Church of Scientology', 'rich-chosen goofy cult'));
console.log(isAnagram('McDonald\'s restaurants', 'Uncle Sam\'s standard rot'));

Benefits

This code complexity is O(n), it depends on string length and takes that much time to provide the output.

Thank you!

--

--

Jitendra Davariya
Jitendra Davariya

Written by Jitendra Davariya

I am a Frontend Engineer having 9 years of hands-on experience in HTML, CSS, and Javascript & Good exposure to develop PWA in ReactJs with Typescript and SCSS

No responses yet