Letter Case Permutation
Difficulty: Medium · Pattern: Backtracking · LeetCode #784
You may change any letter of s to lowercase or uppercase. Return all strings you can create, in any order.
Examples
text
"a1b2" → ["a1b2","a1B2","A1b2","A1B2"]
"3z4" → ["3z4","3Z4"]
"12345" → ["12345"]Hints
- Each letter is a binary choice. Digits have only one option.
Approach
Iterative doubling: start with [""]. For each character, extend every partial string with c.lower() and c.upper() if c is a letter, otherwise just with c. With L letters there are 2^L results. It's the same shape as Subsets: a binary decision per position.
Complexity
Time: O(n · 2^L). Space: O(n · 2^L) for the output.
Python solution
def letterCasePermutation(s):
res = ['']
for ch in s:
if ch.isalpha():
res = [p + c for p in res for c in (ch.lower(), ch.upper())]
else:
res = [p + ch for p in res]
return resJavaScript solution
function letterCasePermutation(s) {
let res = [''];
for (const ch of s) {
if (/[a-z]/i.test(ch)) res = res.flatMap((p) => [p + ch.toLowerCase(), p + ch.toUpperCase()]);
else res = res.map((p) => p + ch);
}
return res;
}