Search This Blog

2024/04/04

Javascript Interview Question:Permutaions of string ( FreeCodeCamp)

Problem Statement:
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 case a repeating.

Test Cases:
Input "aab" should return 2
Input "aaa" should return 0
Input "aabb" should return 8
Input "abcdefa" should return 3600
Input "abfdefa" should return 2640
Input "zzzzzzzz" should return 0
Input "a" should return 1
Input "aaab" should return 0
Input "aaabb" should return 12

Solution:
function permute(str) {
let result = [];
if (str.length == 1) {
return [str];
}

for (let i = 0; i < str.length; i++) {
let firstElement = str.split("")[i]; //first element

//remaining element array
let remaining = str
.split("")
.filter((elem, index) => {
if (index != i) {
return true;
}
})
.join("");

let perms = permute(remaining);
for (let j = 0; j < perms.length; j++) {
perms[j] = perms[j] + firstElement;
}

result.push(...perms);
}

//remove element with same consecutative chars
let finalResult=[]
for (k = 0; k < result.length; k++) {
if(!findRepetation(result[k])){
finalResult.push(result[k])
}
}
return finalResult;
}

function findRepetation(str) {
for (let i = 0; i < str.length - 1; i++) {
let iThChar = str[i];
let iPlusOneThChar = str[i + 1];

if (iThChar == iPlusOneThChar) {
return true;
}
}
return false;
}

let str = "abfdefa";
let result = permute(str);
console.log("RESULT:",result);
console.log("Total Permutaions:",result.length);

No comments:

Post a Comment