Good afternoon! Here's our prompt for today.
Write an algorithm that takes an input string like "abc"
, and prints out all possible permutations of the string. A permutation
of a group of elements is defined as one of the n!
number possible arrangements the elements can take, where n
is the number of elements in the range.
We'd expect the following to hold true, note the permutations printed out:
1const str = "abc"
2permutations(str)
3// abc
4// acb
5// bac
6// bca
7// cba
8// cab
A hint here: break the problem down, and think about what steps are going to be repeated. How would we get from "abc"
to "acb"
?
Constraints
- The string will only consist of lowercase letters
- Length of the string <=
7
- Expected time complexity :
O(n*n!)
- Expected space complexity :
O(n*n!)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
71
"assert.deepEqual(permutations('rand'), [ 'rand', 'radn', 'rnad', 'rnda', 'rdan', 'rdna', 'arnd', 'ardn', 'anrd', 'andr', 'adrn', 'adnr', 'nrad', 'nrda', 'nard', 'nadr', 'ndra', 'ndar', 'dran', 'drna', 'darn', 'danr', 'dnra', 'dnar' ])"
var assert = require('assert');
​
function permutations(str) {
// Fill in this method
return str;
}
​
console.log(permutations('abc'));
​
try {
assert.deepEqual(permutations('abc'), [
'abc',
'acb',
'bac',
'bca',
'cab',
'cba',
]);
​
console.log(
'PASSED: ' +
"assert.deepEqual(permutations('abc'), ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'])"
);
} catch (err) {
console.log(err);
}
​
try {
assert.deepEqual(permutations('a'), ['a']);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's a video of us explaining the solution.
To change the speed of the video or see it in full screen, click the icons to the right of the progress bar.

Here's our guided, illustrated walk-through.
How do I use this guide?