You are given a string s made of letters and digits. Each letter may be written in lowercase or in uppercase, independently of the others. Digits stay as they are.
Return every distinct string you can make this way, in any order.
Example 1
Input: s = "x5y" Output: ["x5y", "x5Y", "X5y", "X5Y"] Why: two letters, two cases each: 2 × 2 = 4 strings
2 more examples and the constraints
Example 2
Input: s = "42" Output: ["42"] Why: no letters, so the string itself is the only one
Example 3
Input: s = "Ab" Output: ["ab", "aB", "Ab", "AB"] Why: the starting case of a letter does not matter
Constraints
- 1 ≤ length of s ≤ 12
- s holds only English letters (either case) and the digits 0 to 9
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Try every mask, then dedupeO(2^n · n)
- Backtrack on letters onlyO(2^L · n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10 digits and 2 letters | Verdict |
|---|---|---|---|
| Try every mask, then dedupe | O(2^n · n) | Wasted on digits | |
| Backtrack on letters only | O(2^L · n) | Best; one visit per answer |
n = length of s, L = number of letters in s.
Edge cases to test
- No letters. "42" returns just ["42"].
- One letter. "a" returns ["a", "A"].
- Input already in mixed case. "Ab" still gives four strings; the starting case is irrelevant.
- All letters at the limit. Ten letters give 1,024 strings; twelve would give 4,096.
- Digits between letters. "1a2B3c" gives 8 strings with the digits fixed in place.
Common mistakes
- Branching on digits too, which makes duplicate strings.
- Appending the same mutable list to the result instead of a fresh string copy.
- Toggling the case with swap and forgetting that the starting case of a letter can be upper.
How to talk through it
- 1Clarify. Only letters and digits? Does the order of the output matter? Must duplicates be avoided?
- 2Count the answers. Each letter doubles the count, so there are 2^L strings; the output alone is that big.
- 3Give the simple idea. A bitmask over all positions plus a set works, but wastes work on digits.
- 4Code the backtracking. Recurse position by position; branch twice only on letters.
- 5Test out loud. Run a digit-only string, a single letter and the mixed-case example.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?