Letter Combinations of a Phone Number
Letter Combinations of a Phone Number
BacktrackingRecursion
Problem Statement
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.
Example
Example 1:
Input: digits = "23"
ad
ae
af
bd
be
bf
cd
ce
cf
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Solution
This is a classic backtracking problem. We can map each digit to its corresponding letters. Then, we use a recursive function to explore all possible combinations. The function will take the current index of the digits string and the combination built so far.
Algorithm Steps
- Create a mapping from digits to letters (e.g., a hash map or an array).
- Define a recursive function `backtrack(index, currentString)`.
- If `currentString` has the same length as the input `digits`, we've formed a complete combination. Add it to our results and return.
- Get the letters corresponding to the digit at the current `index`.
- Iterate through these letters:
- Append the letter to `currentString`.
- Recursively call `backtrack(index + 1, currentString)`.
- Backtrack: remove the letter from `currentString`.
- Initial call: `backtrack(0, "")`.
Letter Combinations Visualization
Step-by-step backtracking algorithm
Progress1 / 1
Ready to start the visualization
Input Digits
2
3
Current Combination
""
Resulting Combinations
No solutions found yet...
Letter Combinations Solution