Last active
September 19, 2021 21:54
-
-
Save lparolari/59f264e1e63d0987d8373d61a865c579 to your computer and use it in GitHub Desktop.
A straightforward solution for "No Repeats Please" coding interview exercise at freecodecamp.org (https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/no-repeats-please)
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
// A straightforward solution for "No Repeats Please" | |
// coding interview exercise at freecodecamp.org | |
// (https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/no-repeats-please) | |
// | |
// Luca Parolari | |
// | |
// GitHub: github.com/lparolari | |
// Email: luca.parolari23@gmail.com | |
// Telegram: @lparolari | |
function genPerm(str) { | |
/* base case */ | |
if (str.length == 1) return [str]; | |
/* inductive case */ | |
let res = [] | |
for (let i = 0; i < str.length; i++) { | |
const a = str[i] | |
const substr = str.substring(0, i) + str.substring(i + 1, str.length) | |
const perms = genPerm(substr) | |
for (const perm of perms) { | |
res.push(a + perm) | |
} | |
} | |
return res; | |
} | |
function hasRepeatedConsecutiveLetters(str) { | |
for (let i = 0; i < str.length - 1; i++) { | |
if (str[i] === str[i + 1]) { | |
return true; | |
} | |
} | |
return false; | |
} | |
function permAlone(str) { | |
const perms = genPerm(str) | |
let counter = 0 | |
for (const perm of perms) { | |
if (!hasRepeatedConsecutiveLetters(perm)) { | |
counter ++; | |
} | |
} | |
return counter; | |
} | |
permAlone('aab'); // 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment