Skip to main content

Letter Case Permutation

Question

Given a string, write an algorithm to generate all possible letter case permutations of the string.

Example 1
Input: "a1b2"

Output: ["a1b2", "a1B2", "A1b2", "A1B2"]

Solution

all//Letter Case Permutation.py


def letter_case_permutation(s):
result = []
for i in range(len(s)):
if s[i].isalpha():
result += [s[:i] + l + s[i+1:] for l in [s[i].lower(), s[i].upper()]]
return result if result else [s]

# test
s = "a1b2"
print(letter_case_permutation(s)) # output: ["a1b2", "a1B2", "A1b2", "A1B2"]