From 96a5e6bff1749546fbd0e04f4f1c287886f18d83 Mon Sep 17 00:00:00 2001 From: Manish Date: Tue, 22 Aug 2023 10:51:06 +1000 Subject: [PATCH] Algorithms: No Repeats Please --- Algorithms/noRepeatsPlease.js | 37 +++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Algorithms/noRepeatsPlease.js 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"));