Letter Case Permutation — LeetCode 784 Python Solution
- Problem
- #784
- Pattern
- Backtracking
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.
Example
- Input
- s = "a1b2"
- Output
- ["a1b2","a1B2","A1b2","A1B2"]
Python solution
class Solution:
def letterCasePermutation(self, s: str) -> List[str]:
def dfs(i: int) -> None:
if i >= len(t):
ans.append("".join(t))
return
dfs(i + 1)
if t[i].isalpha():
t[i] = chr(ord(t[i]) ^ 32)
dfs(i + 1)
t = list(s)
ans = []
dfs(0)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times 2^n), where n is the length of the string s |
| Space | O(depth) auxiliary |
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 784. Letter Case Permutation is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 784. Letter Case Permutation?
- LeetCode 784. Letter Case Permutation is rated Medium on LeetCode.
- What is the time complexity of LeetCode 784. Letter Case Permutation?
- The Python solution on this page runs in O(n \times 2^n), where n is the length of the string s.
- What is the space complexity of LeetCode 784. Letter Case Permutation?
- The Python solution on this page uses O(depth) auxiliary space.
- What topics does LeetCode 784. Letter Case Permutation cover?
- LeetCode 784. Letter Case Permutation is tagged Bit Manipulation, String and Backtracking on LeetCode.