Home
DSA Patterns
Backtracking
Letter Case Permutation
Letter Case Permutation (LeetCode 784)
Letter Case Permutation (LeetCode 784): generate every string from changing each letter's case with backtracking: each letter branches into lower and upper case, digits pass through.
Problem Understanding
Letter Case Permutation: given a string s of letters and digits, return every string you can make by changing each letter to lower or upper case, in any order.
Example: s = "a1b2" returns ["a1b2", "a1B2", "A1b2", "A1B2"].
The Intuition: A Binary Choice per Letter
Every letter is a yes/no choice (lower or upper), and every digit is fixed. That is a binary decision tree, explored with backtracking:
- At index
i, a digit has one child: move toi + 1. - A letter has two children: lower case, then upper case.
- A full path is one answer.
It is the same "choose for each position" shape as Subsets, where each element is in or out, and Letter Combinations of a Phone Number, where each digit has several letters.
Letter Case Permutation Visualization
START AT INDEX 0
current string
0
1
2
3
results (0)
None yet
Walk "a1b2" one character at a time; each letter splits into two branches
Next
Index 0: 'a' is a letter. Branch 1: lower case 'a'
s
The string being built is shown with the current index filled; characters already fixed on this branch are tinted. Recorded strings collect beside it. Try Four letters to watch 16 strings appear.
Letter Case Permutation Dry Run
Input: s = "a1b2"
| [0] a | [1] 1 | [2] b | [3] 2 | Result |
|---|---|---|---|---|
| a | 1 | b | 2 | a1b2 |
| a | 1 | B | 2 | a1B2 |
| A | 1 | b | 2 | A1b2 |
| A | 1 | B | 2 | A1B2 |
Answer: 4 strings (2 letters, 2² = 4).
Letter Case Permutation LeetCode Solution
Backtracking over a mutable copy of the string. C sizes the result as 2^k up front.
Letter Case Permutation Code
1var letterCasePermutation = function(s) {2 const res = [], path = s.split('');3 const backtrack = (i) => {4 if (i === s.length) {5 res.push(path.join(''));6 return;7 }8 if (/[a-z]/i.test(s[i])) {9 path[i] = s[i].toLowerCase();10 backtrack(i + 1);11 path[i] = s[i].toUpperCase();12 backtrack(i + 1);13 } else {14 backtrack(i + 1);15 }16 };17 backtrack(0);18 return res;19};
Letter Case Permutation in Python, Java, C++, TypeScript and C
Letter Case Permutation in Python
class Solution:
def letterCasePermutation(self, s: str) -> List[str]:
res, path = [], list(s)
def backtrack(i):
if i == len(s):
res.append(''.join(path))
return
if s[i].isalpha():
path[i] = s[i].lower()
backtrack(i + 1)
path[i] = s[i].upper()
backtrack(i + 1)
else:
backtrack(i + 1)
backtrack(0)
return resLetter Case Permutation in Java
class Solution {
public List<String> letterCasePermutation(String s) {
List<String> res = new ArrayList<>();
backtrack(s.toCharArray(), 0, res);
return res;
}
private void backtrack(char[] path, int i, List<String> res) {
if (i == path.length) {
res.add(new String(path));
return;
}
if (Character.isLetter(path[i])) {
path[i] = Character.toLowerCase(path[i]);
backtrack(path, i + 1, res);
path[i] = Character.toUpperCase(path[i]);
backtrack(path, i + 1, res);
} else {
backtrack(path, i + 1, res);
}
}
}Letter Case Permutation in C++
class Solution {
public:
vector<string> letterCasePermutation(string s) {
vector<string> res;
backtrack(s, 0, res);
return res;
}
private:
void backtrack(string& path, int i, vector<string>& res) {
if (i == (int)path.size()) {
res.push_back(path);
return;
}
if (isalpha(path[i])) {
path[i] = tolower(path[i]);
backtrack(path, i + 1, res);
path[i] = toupper(path[i]);
backtrack(path, i + 1, res);
} else {
backtrack(path, i + 1, res);
}
}
};Letter Case Permutation in TypeScript
function letterCasePermutation(s: string): string[] {
const res: string[] = [], path = s.split('');
const backtrack = (i: number): void => {
if (i === s.length) {
res.push(path.join(''));
return;
}
if (/[a-z]/i.test(s[i])) {
path[i] = s[i].toLowerCase();
backtrack(i + 1);
path[i] = s[i].toUpperCase();
backtrack(i + 1);
} else {
backtrack(i + 1);
}
};
backtrack(0);
return res;
}Letter Case Permutation in C
void backtrack(char* path, int i, int n, char** res, int* count) {
if (i == n) {
res[*count] = malloc(n + 1);
memcpy(res[*count], path, n + 1);
(*count)++;
return;
}
if (isalpha(path[i])) {
path[i] = tolower(path[i]);
backtrack(path, i + 1, n, res, count);
path[i] = toupper(path[i]);
backtrack(path, i + 1, n, res, count);
} else {
backtrack(path, i + 1, n, res, count);
}
}
char** letterCasePermutation(char* s, int* returnSize) {
int n = strlen(s), letters = 0;
for (int i = 0; i < n; i++) if (isalpha(s[i])) letters++;
char** res = malloc((1 << letters) * sizeof(char*));
*returnSize = 0;
backtrack(s, 0, n, res, returnSize);
return res;
}Edge Cases & Common Mistakes
- No letters: the only result is the string itself.
- Upper-case input letters: set both cases explicitly instead of toggling, so
"C"still gives"c"and"C". - Branching on digits: produces duplicate strings; digits have only one option.
- Sharing one mutable buffer: fine in this template: every letter position is set again on each branch before the string is recorded, so leftovers from an earlier branch never leak in.
- Order: any order is accepted; this template lists lower-case branches first.
Summary
Walk the string by index. Digits pass straight through; each letter branches into lower and upper case. Record the string when the index reaches the end. k letters give 2^k strings, in O(n · 2^k) time.
More practice: DSA interview questions with answers · patterns cheat sheet
