Letter Case Permutation (LeetCode 784): Solution and Explanation
Return every string you can make from s by switching each letter, independently, between lowercase and uppercase. Digits stay as they are.
Intuition
Digits have one form and letters have two. So the answer is a product of independent two-way choices, one per letter, and with k letters there are exactly 2^k strings.
Independent yes/no choices are exactly what the bits of a number encode. Number the letters 0..k-1 and let bit b of a mask say whether letter b is uppercase.
Counting the mask from 0 to 2^k - 1 visits every on/off pattern once, so building one string per mask lists every answer with no duplicates and no recursion.
Approach: Bitmask enumeration
- Record the indices of the letters in
s; call the countk. - For each
maskfrom 0 to2^k - 1, start from the all-lowercase copy ofs. - For each bit
bset inmask, uppercase the letter atletters[b]. - Append the string. After the loop the list holds all
2^kstrings.
Step-by-step example
s = "a1b2"
- Letters are at indices 0 ('a', bit 0) and 2 ('b', bit 1), so k = 2 and there are 4 masks.
- mask = 00: nothing uppercase, append "a1b2".
- mask = 01: bit 0 set, uppercase 'a', append "A1b2".
- mask = 10: bit 1 set, uppercase 'b', append "a1B2".
- mask = 11: both set, append "A1B2". Result: ["a1b2","A1b2","a1B2","A1B2"].
Code: Python, Java, C++
1class Solution:
2 def letterCasePermutation(self, s: str) -> List[str]:
3 letters = [i for i, c in enumerate(s) if c.isalpha()]
4 result = []
5 for mask in range(1 << len(letters)):
6 chars = list(s.lower())
7 for bit, pos in enumerate(letters):
8 if mask >> bit & 1:
9 chars[pos] = chars[pos].upper()
10 result.append(''.join(chars))
11 return result1class Solution {
2 public List<String> letterCasePermutation(String s) {
3 List<Integer> letters = new ArrayList<>();
4 for (int i = 0; i < s.length(); i++) {
5 if (Character.isLetter(s.charAt(i))) letters.add(i);
6 }
7 List<String> result = new ArrayList<>();
8 for (int mask = 0; mask < (1 << letters.size()); mask++) {
9 char[] chars = s.toLowerCase().toCharArray();
10 for (int bit = 0; bit < letters.size(); bit++) {
11 if (((mask >> bit) & 1) == 1) {
12 int pos = letters.get(bit);
13 chars[pos] = Character.toUpperCase(chars[pos]);
14 }
15 }
16 result.add(new String(chars));
17 }
18 return result;
19 }
20}1class Solution {
2public:
3 vector<string> letterCasePermutation(string s) {
4 vector<int> letters;
5 for (int i = 0; i < (int) s.size(); i++) {
6 if (isalpha(s[i])) letters.push_back(i);
7 }
8 vector<string> result;
9 for (int mask = 0; mask < (1 << letters.size()); mask++) {
10 string chars = s;
11 for (char& c : chars) c = tolower(c);
12 for (int bit = 0; bit < (int) letters.size(); bit++) {
13 if ((mask >> bit) & 1) {
14 chars[letters[bit]] = toupper(chars[letters[bit]]);
15 }
16 }
17 result.push_back(chars);
18 }
19 return result;
20 }
21};Time and space complexity
O(n 2^k)
There are 2^k masks, and each one builds a string of length n. k is at most n, so this is O(n 2^n) in the worst case.
O(n)
Apart from the output, we keep the letter positions and one working copy of the string.
Other approaches
Backtracking (time O(n 2^k), space O(n) recursion)
Walk the string left to right. At a digit, move on; at a letter, recurse once with lowercase and once with uppercase. Append when you reach the end.
Iterative doubling (time O(n 2^k), space O(n 2^k))
Start with [""]. For each character, extend every partial string by it; for a letter, extend each one twice, once per case. The list doubles at every letter.
Common mistakes
- Treating digits as choices. Branching on a digit produces duplicate strings.
- Starting from s as given instead of from a lowercase copy. If s already has uppercase letters, mask 0 would not be the all-lowercase string and some strings would repeat while others go missing.
- Using 1 << n (string length) instead of 1 << k (letter count). The extra masks map to duplicate strings.
Frequently asked questions
Does the order of the output matter?
No. Any order is accepted as long as every string appears exactly once.
Why is the mask approach guaranteed to produce no duplicates?
Two different masks differ in some bit b, so the strings they build differ in the case of letter b. Different masks always give different strings.
What if the string has no letters?
Then k = 0, the only mask is 0, and the answer is just [s].