Letter Case Permutation — LeetCode 784 Python Solution

MediumBit ManipulationStringBacktracking
Problem
#784
Reading time
3 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n \times 2^n), where n is the length of the string s
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview