In this post, we will see how to list out all permutations of a string in Python.

For example, the string ABC has 6 permutations, i.e., ABC, ACB, BAC, BCA, CBA, CAB.

Practice this problem

In Python, we can use the built-in module itertools to get permutations of elements in the list using the permutations() function.

 
However, we can also write your utility function to generate all permutations of a string. We can do this either recursively or iteratively.

1. Recursive Implementation

The idea is to convert the given string to a character array, and in-place generate all its permutations using backtracking.

We can do this by swapping each of the remaining characters in the string with its first character and generating all the permutations of the remaining characters using a recursive call. This is illustrated in the recursion tree shown below.

Permutations of a String

Download  Run Code

Output:

ABC
ACB
BAC
BCA
CBA
CAB

 
Here’s another implementation in Python which doesn’t convert the string to a character array.

Download  Run Code

Output:

ABC
ACB
BAC
BCA
CBA
CAB

2. Iterative Implementation

The idea is to store the partially generated permutations and then use those partial permutations to generate the final permutations in further iterations. Here’s how the code would look like:

Download  Run Code

Output:

[‘CAB’, ‘ACB’, ‘ABC’, ‘CBA’, ‘BCA’, ‘BAC’]

 
The time complexity of the above solutions is O(n.n!) since there are n! permutations for a string of length n, and each permutation takes O(n) time.