Last active
December 7, 2019 20:30
-
-
Save deemaxx/5b672d002d9157631247ddf9b0755b84 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Do two given strings form an anagram? | |
// Possible solution should not be a higher Big O notation than O(n). | |
// Evaluation is case insensitive. | |
/** | |
* @param str1 | String | |
* @param str2 | String | |
* @return Boolean | |
*/ | |
const isItAnAnagram = (str1, str2) => { | |
// type check arguments passed | |
if (typeof str1 !== 'string' || typeof str2 !== 'string') { | |
return false | |
} | |
// Normalize strings by lower casing them, and by removing any spaces | |
const stringOne = str1.toLowerCase().replace(/\s/g, '') | |
const stringTwo = str2.toLowerCase().replace(/\s/g, '') | |
// check first if the two strings are of same length. If not return false and stop further execution. | |
if (stringOne.length !== stringTwo.length) { | |
return false | |
} | |
// Also check if the strings are identical. If yes, the second string is not considered an anagram. | |
if (stringOne === stringTwo) { | |
return false | |
} | |
// create an object for each string. | |
let stringObject1 = {} | |
let stringObject2 = {} | |
// loop through each char adding it as a property to the object if it | |
// is not yet present and assign the value of 1. | |
// Othwerwise if the char already exists as a property add 1 count. | |
for (let char of stringOne) { | |
stringObject1[char] = stringObject1[char] + 1 || 1 | |
} | |
for (let char of stringTwo) { | |
stringObject2[char] = stringObject2[char] + 1 || 1 | |
} | |
// iterate over first object and check for a corresponding char | |
// in the seocnd object. If one found, check for equal count value. | |
for (let char in stringObject1) { | |
// If no match return false. | |
if (!stringObject2.hasOwnProperty(char)) { | |
return false | |
} | |
// If no match return false. | |
if (stringObject1[char] !== stringObject2[char]) { | |
return false | |
} | |
// Second string argument is an anagram of the first string argument. | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment