Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Return the number of total permutations of the provided string that don't have repeated consecutive letters. Assume that all characters in the provided string are each unique. For example, aab should return 2 because it has 6 total permutations (aab, aab, aba, aba, baa, baa), but only 2 of them (aba and aba) don't have the same letter (in this c…
function permAlone(str) {
//check if the string provided is only one character
if(str.length === 1){
return 1;
//function to create the permutations
//for each value in the string, add the permutations of the rest
function getPermutations(str){
var output = [];
//to test for doubles, between brackets capture any letter then match it again,
//the '1' indicates captured group 1 (similar to $1)
var regex = /([a-z])\1/i;
//check the length of the string, if it's one return it to build the new string
if(str.length === 1){
return str;
//for every first letter... (recursion function)
for(var i = 0; i<str.length; i++){
//make a copy of the string less one character
var tempStr = str.substring(0, i) + str.substring(i+1);
var char = str[i]; //hold the first letter
//recall the function with the smaller string
var permutations = getPermutations(tempStr);
//loop through the new permutations and add the first character to each.
for(var j = 0; j<permutations.length; j++){
//check new string against regex and only add those with no doubles
if(!regex.test(char + permutations[j]) ){
output.push(char + permutations[j]);
return output;
//call the permutations function for the string provided
var permutes = getPermutations(str);
//return the number of permutations without doubles
return permutes.length;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment