Created
January 17, 2018 21:01
-
-
Save mayashavin/c213d20dc7aea8ebbc24718f93883ad9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function isPermutation(strA, strB){ | |
var isValid = true; | |
//First validity check | |
if (!strA || !strB || strA.length !== strB.length){ | |
return !isValid; | |
} | |
//Get the map of characters and their occurences in strA | |
var charsMap = getMap(strA); | |
//Check strB characters and occurences on the computed map. | |
for (var i = 0; i < strB.length; i++){ | |
var charB = strB[i]; | |
if (charsMap[charB] !== undefined && charsMap[charB] >= 1){ | |
charsMap[charB]--; // If current character does appear in A and B, decrement the occurence counter. | |
} | |
else{ | |
return !isValid; | |
} | |
} | |
return isValid; | |
} | |
function getMap(str){ | |
var map = {}; | |
for (var i = 0; i < str.length; i++){ | |
var currChar = str[i]; | |
//If current character hasn't been mapped, map it | |
if (map[currChar] === undefined){ | |
map[currChar] = 1; | |
} | |
else{ | |
map[currChar]++; //Else increment the occurrence counter. | |
} | |
} | |
return map; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment