Member-only story

String Permutations in JS

Jack
Jan 4, 2021

--

Given a string, return an array of all possible permutations.

For example, given ‘abc’ the function should return [ ‘abc’, ‘acb’, ‘bac’, ‘bca’, ‘cab’, ‘cba’ ].

This problem can get tricky quite quickly. Something important to identify within this solution is that we can use recursion. At each step, we afix the first letter and permute the rest of the string.

So, findAllPermutations(‘abc’) =

‘a’ + findAllPermutations(‘bc’) +

‘b’ + findAllPermutations(‘ac’) +

‘c’ + findAllPermutations(‘ab’)

To acheive this, we will use a double for loop. Within the first loop, we set our ‘fixed’ first character and also set a variable for the remaining characters.

Then, within the second loop, we iterate over all permutations of remainingChars by means of recursion. Lastly, we push that permutation into array results and return results outside the loop. (Notice how we return str if str.length === 1)

--

--

Jack
Jack

Written by Jack

Magician, Mathematician, and Software Engineer

No responses yet