diff --git a/Algorithms/noRepeatsPlease.js b/Algorithms/noRepeatsPlease.js new file mode 100644 index 0000000..1593c16 --- /dev/null +++ b/Algorithms/noRepeatsPlease.js @@ -0,0 +1,37 @@ +// 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"));