Good morning! 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:
1str = "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
​
def permutations(string):
# fill in
return string
​
​
import unittest
​
​
class Test(unittest.TestCase):
def test_1(self):
assert permutations("abc") == ["abc", "acb", "bac", "bca", "cab", "cba"]
print(
"PASSED: assert permutations('abc') == ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']"
)
​
def test_2(self):
assert permutations("a") == ["a"]
print("PASSED: assert permutations('a') == ['a']")
​
def test_3(self):
assert permutations("rand") == [
"rand",
"radn",
"rnad",
"rnda",
"rdan",
"rdna",
"arnd",
"ardn",
Tired of reading? Watch this video explanation!
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 how we would solve this problem...
How do I use this guide?
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.