Created
May 2, 2023 22:38
-
-
Save optimistiks/0ccb0b36ca6a330677512a758f4d38fa to your computer and use it in GitHub Desktop.
Given an input string, return all possible permutations of the string.
This file contains hidden or 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
| 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
