Letter Case Permutation (LeetCode 784): Solution and Explanation

Medium
String
Backtracking
Bit Manipulation

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

  1. Record the indices of the letters in s; call the count k.
  2. For each mask from 0 to 2^k - 1, start from the all-lowercase copy of s.
  3. For each bit b set in mask, uppercase the letter at letters[b].
  4. Append the string. After the loop the list holds all 2^k strings.

Step-by-step example

s = "a1b2"
  1. Letters are at indices 0 ('a', bit 0) and 2 ('b', bit 1), so k = 2 and there are 4 masks.
  2. mask = 00: nothing uppercase, append "a1b2".
  3. mask = 01: bit 0 set, uppercase 'a', append "A1b2".
  4. mask = 10: bit 1 set, uppercase 'b', append "a1B2".
  5. 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 result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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].