Letter Case Permutation

Generate every case-variant of a string — DFS with two choices per letter.

Medium
Time O(2^n * n) Space O(n)
LeetCode
3 min read
subsets backtracking string

Problem#

Given a string with letters and digits, return all strings obtained by independently toggling the case of each letter.

Examples#

  • "a1b2"["a1b2","a1B2","A1b2","A1B2"]

Constraints#

  • 1 <= s.length <= 12.

Approach#

DFS. At each position: if digit, recurse with one choice. If letter, recurse twice with each case.

Solution#

Letter Case Permutation
class Solution {
public:
vector<string> letterCasePermutation(string s) {
vector<string> out;
function<void(int)> dfs = [&](int i){
if (i == (int)s.size()) { out.push_back(s); return; }
dfs(i + 1);
if (isalpha((unsigned char)s[i])) {
s[i] ^= 0x20; // toggle case (ASCII)
dfs(i + 1);
s[i] ^= 0x20;
}
};
dfs(0);
return out;
}
};

Editorial#

Each letter contributes a factor of 2 to the count. The ^= 0x20 trick toggles case in ASCII without branching on which case we’re in — uppercase and lowercase letters differ only in bit 5.

Complexity#

  • Time: O(2^L * n) where L is letter count.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.