Skip to content

Instantly share code, notes, and snippets.

@optimistiks
Created May 2, 2023 22:38
Show Gist options
  • Select an option

  • Save optimistiks/0ccb0b36ca6a330677512a758f4d38fa to your computer and use it in GitHub Desktop.

Select an option

Save optimistiks/0ccb0b36ca6a330677512a758f4d38fa to your computer and use it in GitHub Desktop.
Given an input string, return all possible permutations of the string.
function swap(word, i, j) {
let swapIndex = word.split("");
let temp = swapIndex[j];
swapIndex[j] = swapIndex[i];
swapIndex[i] = temp;
return swapIndex.join("");
}
function permuteStringRec(word, pointer, result) {
// pointer is a number indication an index of a character in the string
// everything to the left from the pointer is "fixed" (we don't swap it or touch in any way)
// if pointer points to the last character, there is nothing left to swap, so it's the base case
if (pointer === word.length - 1) {
result.push(word);
}
// otherwise, repeatedly swap character at pointer with every character after pointer
// and call the same function recursively with the swapped word, but with incremented pointer
// so for example in case of word=xyz it will give us
// initial call: word=xyz, pointer=0 (0 will be swapped with 0, 1 and 2)
// it will produce 3 following recursive calls:
// word=xyz pointer=1, word=yxz pointer=1, word=zyx pointer=1
// in all those 3 cases, the first character is "fixed", and only 2 last characters are swapped
// this way our recursive calls cover all the permutations
for (let i = pointer; i < word.length; ++i) {
permuteStringRec(swap(word, pointer, i), pointer + 1, result);
}
}
export function permuteWord(word) {
let result = [];
permuteStringRec(word, 0, result);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment