Skip to content

Instantly share code, notes, and snippets.

@mayashavin
Created January 17, 2018 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayashavin/c213d20dc7aea8ebbc24718f93883ad9 to your computer and use it in GitHub Desktop.
Save mayashavin/c213d20dc7aea8ebbc24718f93883ad9 to your computer and use it in GitHub Desktop.
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