Introduction
The Letter Case Permutation problem is a classic example of recursion and backtracking, often asked in coding interviews and frequently searched by learners preparing for platforms like LeetCode.
This problem helps in understanding:
- Decision-making at each step
- Recursive branching
- String manipulation
In this article, weβll break down the intuition, visualize the decision process using your decision tree, and implement an efficient Java solution.
π Problem Link
LeetCode: Letter Case Permutation
Problem Statement
Given a string s, you can transform each alphabet character into:
- Lowercase
- Uppercase
Digits remain unchanged.
π Return all possible strings formed by these transformations.
Examples
Example 1
Input:
s = "a1b2"
Output:
["a1b2","a1B2","A1b2","A1B2"]
Example 2
Input:
s = "3z4"
Output:
["3z4","3Z4"]
Key Insight
At each character:
- If it's a digit β only one choice
- If it's a letter β two choices:
So total combinations:
Intuition (Using Your Decision Tree)
For input: "a1b2"
Start from index 0:
Understanding the Tree
- At
'a'β branch into'a'and'A' '1'β no branching (digit)'b'β again branching'2'β no branching
π Leaf nodes = final answers
Approach: Recursion + Backtracking
Idea
- Traverse the string character by character
- If digit β move forward
- If letter β branch into:
- lowercase
- uppercase
Java Code
Step-by-Step Execution
For "a1b2":
- Start β
"" 'a'β"a","A"'1'β"a1","A1"'b'β"a1b","a1B","A1b","A1B"'2'β final strings
Complexity Analysis
- Time Complexity: O(2^n)
- (n = number of letters)
- Space Complexity: O(2^n)
- (for storing results)
Why This Approach Works
- Recursion explores all possibilities
- Each letter creates a branching point
- Digits pass through unchanged
- Backtracking ensures all combinations are generated
Key Takeaways
- This is a binary decision recursion problem
- Letters β 2 choices
- Digits β 1 choice
- Decision tree directly maps to recursion
- Pattern similar to:
- Subsets
- Permutations with conditions
When This Problem Is Asked
Common in:
- Coding interviews
- Recursion/backtracking rounds
- String manipulation problems
Conclusion
The Letter Case Permutation problem is a perfect example of how recursion can be used to explore all possible combinations efficiently.
Once the decision tree is clear, the implementation becomes straightforward. This pattern is widely used in many advanced problems, making it essential to master.
Frequently Asked Questions (FAQs)
1. Why donβt digits create branches?
Because they have only one valid form.
2. What is the main concept used?
Recursion with decision-making (backtracking).
3. Can this be solved iteratively?
Yes, using BFS or iterative expansion, but recursion is more intuitive.





