Generate every permutation of a string with recursive backtracking in O(n·n!). Compare with itertools.permutations and test it in your browser.
The problem
Return a list of every permutation of s (assume its characters are distinct). Order of the list does not matter. Do not use itertools.
Examples
Example 1
Input
permutations('abc')Expected output
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Example 2
Input
permutations('ab')Expected output
['ab', 'ba']
+ 2 hidden tests on Submit — 24 results.
Edge cases to ask about
- Single character
- Duplicate characters (follow-up)
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.
Pick both to reveal the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| Pick each character first, permute the rest | O(n · n!) | O(n · n!) | n! results, each n characters long. |
Walkthrough of the optimal approach (try it yourself first)
For each character, fix it as the first and append it to every permutation of the remaining characters. The base case is length ≤ 1.
The output alone has n! entries, so nothing can beat O(n · n!) — the interviewer is checking you know that factorial growth is unavoidable here.
Complexity: O(n · n!) time, O(n · n!) space. There are n! permutations and building each costs O(n); storing them all needs the same.
Reveal the reference solution
def permutations(s): if len(s) <= 1: return [s] out = [] for i, ch in enumerate(s): for rest in permutations(s[:i] + s[i + 1:]): out.append(ch + rest) return out
Follow-ups interviewers ask
- Handle duplicate characters without duplicate results.
- Yield them lazily with a generator.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Generate All Permutations of a String in Python?
The optimal solution runs in O(n · n!) time and O(n · n!) auxiliary space. There are n! permutations and building each costs O(n); storing them all needs the same.
What follow-up questions do interviewers ask about Generate All Permutations of a String?
Handle duplicate characters without duplicate results. Yield them lazily with a generator.
