Python Program to Find All Permutations of a String
itertools.permutations(string) or by writing a recursive function that swaps characters to generate all possible orders.Examples
How to Think About It
Algorithm
Code
from itertools import permutations def all_permutations(s): return [''.join(p) for p in permutations(s)] print(all_permutations('abc'))
Dry Run
Let's trace the input 'abc' through the itertools permutations code.
Input string
s = 'abc'
Generate permutations
permutations('abc') generates tuples: ('a','b','c'), ('a','c','b'), ('b','a','c'), ('b','c','a'), ('c','a','b'), ('c','b','a')
Join tuples to strings
Each tuple is joined to form strings: 'abc', 'acb', 'bac', 'bca', 'cab', 'cba'
Return list
Return list of all these strings.
| Permutation Tuple | Joined String |
|---|---|
| ('a','b','c') | abc |
| ('a','c','b') | acb |
| ('b','a','c') | bac |
| ('b','c','a') | bca |
| ('c','a','b') | cab |
| ('c','b','a') | cba |
Why This Works
Step 1: Using itertools.permutations
The permutations function generates all possible orderings of the input characters as tuples.
Step 2: Joining tuples to strings
Each tuple of characters is joined back into a string to represent one permutation.
Step 3: Collecting all permutations
All these strings are collected into a list and returned as the final result.
Alternative Approaches
def permute(s): if len(s) == 0: return [''] result = [] for i, c in enumerate(s): for perm in permute(s[:i] + s[i+1:]): result.append(c + perm) return result print(permute('abc'))
def backtrack(chars, path, used, res): if len(path) == len(chars): res.append(''.join(path)) return for i in range(len(chars)): if used[i]: continue used[i] = True path.append(chars[i]) backtrack(chars, path, used, res) path.pop() used[i] = False chars = list('abc') result = [] backtrack(chars, [], [False]*len(chars), result) print(result)
Complexity: O(n!) time, O(n!) space
Time Complexity
Generating all permutations requires factorial time because there are n! ways to arrange n characters.
Space Complexity
Storing all permutations requires factorial space since each permutation is stored as a string.
Which Approach is Fastest?
Using itertools.permutations is fastest and most memory-efficient due to optimized C implementation; recursive and backtracking methods are slower and use more memory.
| Approach | Time | Space | Best For |
|---|---|---|---|
| itertools.permutations | O(n!) | O(n!) | Quick, efficient, built-in |
| Recursive function | O(n!) | O(n!) | Learning recursion, clarity |
| Backtracking | O(n!) | O(n!) | Understanding recursion and state |
itertools.permutations for a quick and efficient way to get all permutations of a string.