freeCodeCamp/Algorithms/noRepeatsPlease.js

38 lines
867 B
JavaScript

// https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/no-repeats-please
function permAlone(str) {
let noRepeatsCount = 0;
noRepeatsCount += Number(!/(.{1})\1/.test(str));
function swap(Arr, iA, iB) {
const tmp = Arr[iA];
Arr[iA] = Arr[iB];
Arr[iB] = tmp;
}
const strArr = str.split("");
const strLength = strArr.length;
// Heap's Algorithm as explained @ https://www.baeldung.com/cs/array-generate-all-permutations
const c = Array(strLength).fill(0);
let i = 0;
while (i < strLength) {
if (c[i] < i) {
if (i % 2) {
swap(strArr, c[i], i);
} else {
swap(strArr, 0, i);
}
noRepeatsCount += Number(!/(.{1})\1/.test(strArr.join("")));
c[i]++;
i = 0;
} else {
c[i] = 0;
i++;
}
}
return noRepeatsCount;
}
console.log(permAlone("abcdefa"));