Language Selection
Choose your preferred programming language
Showing: Python
Generate Permutations
Problem Statement
Given a string s, generate all possible permutations of the string.
A permutation is an arrangement of all or part of a set of objects, with regard to the order of the arrangement.
Examples
Example 1:
Input: s = "abc"
Output: ["abc", "acb", "bac", "bca", "cab", "cba"]
Example 2:
Input: s = "ab"
Output: ["ab", "ba"]
Constraints
1 <= s.length <= 6sconsists of lowercase English letters only
Approach 1: Backtracking with Swap
Algorithm
Use backtracking to generate permutations by swapping characters at different positions.
Steps:
- Start with the original string
- For each position, swap with all remaining positions
- Recursively generate permutations for the remaining positions
- Backtrack by swapping back to restore original state
Implementation
Python:
def generate_permutations(s):
"""
Generate all permutations using backtracking with swap
Time: O(n!*n)
Space: O(n!*n)
"""
result = []
chars = list(s)
def backtrack(start):
if start == len(chars):
result.append(''.join(chars))
return
for i in range(start, len(chars)):
# Swap characters
chars[start], chars[i] = chars[i], chars[start]
# Recursively generate permutations
backtrack(start + 1)
# Backtrack
chars[start], chars[i] = chars[i], chars[start]
backtrack(0)
return result
Java:
class Solution {
public List<String> generatePermutations(String s) {
List<String> result = new ArrayList<>();
char[] chars = s.toCharArray();
backtrack(chars, 0, result);
return result;
}
private void backtrack(char[] chars, int start, List<String> result) {
if (start == chars.length) {
result.add(new String(chars));
return;
}
for (int i = start; i < chars.length; i++) {
swap(chars, start, i);
backtrack(chars, start + 1, result);
swap(chars, start, i);
}
}
private void swap(char[] chars, int i, int j) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
}
Complexity Analysis
- Time Complexity: O(n!*n) where n is the length of the string
- Space Complexity: O(n!*n) for storing all permutations
Key Insights
- Backtracking: Use backtracking to explore all possible arrangements
- Swap Approach: Swap characters to generate different permutations
- Permutation Count: For a string of length n, there are n! permutations
- Recursion Base Case: When we’ve used all characters, we have a complete permutation
Edge Cases
- Single character: String with one character
- Two characters: Minimum case with two characters
- All same characters: String with repeated characters
- Maximum length: Handle the constraint limit of 6 characters
Test Cases
# Test cases
assert generate_permutations("abc") == ["abc", "acb", "bac", "bca", "cab", "cba"]
assert generate_permutations("ab") == ["ab", "ba"]
assert generate_permutations("a") == ["a"]
assert len(generate_permutations("abcd")) == 24 # 4! = 24
Follow-up Questions
- Next Permutation: Find the next lexicographically greater permutation
- Permutation Sequence: Find the kth permutation in lexicographic order
- Permutations with Duplicates: Handle strings with duplicate characters
- Permutation in String: Check if one string is a permutation of another
Common Mistakes
- Incomplete backtracking: Not properly restoring state after recursion
- Index errors: Going out of bounds in character arrays
- Duplicate handling: Not handling duplicate characters correctly
- Base case: Incorrect termination condition
Interview Tips
- Start with examples: Walk through the permutation generation process
- Explain backtracking: Show how the recursive approach works
- Handle edge cases: Always consider single character and duplicate cases
- Discuss complexity: Explain why it’s O(n!*n) time complexity
- Trace through algorithm: Show how backtracking works step by step