Problem
Given a string of digits digits, return all possible letter combinations that the number could represent.The mapping of digits to letters is the same as on a traditional telephone keypad. The input contains digits from
2 to 9.
Example(s)
Consider the following example(s) to understand the expected input and output.Input
digits = "23"
Output
["ad","ae","af","bd","be","bf","cd","ce","cf"]
Solution
This solution uses Backtracking to build all possible letter combinations. For each digit, we iterate through all its corresponding letters and add one letter to the current combination.
After each recursive call, the last letter is removed so that the algorithm can explore the next possible letter for the current digit.
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<>();
if (digits == null || digits.isEmpty()) {
return result;
}
String[] mapping = {
"", "", "abc", "def", "ghi",
"jkl", "mno", "pqrs", "tuv", "wxyz"
};
backtrack(digits, 0, new StringBuilder(), result, mapping);
return result;
}
private void backtrack(String digits, int index,
StringBuilder current, List<String> result,
String[] mapping) {
// A complete combination is found.
if (index == digits.length()) {
result.add(current.toString());
return;
}
int digit = digits.charAt(index) - '0';
String letters = mapping[digit];
for (char letter : letters.toCharArray()) {
// Choose the current letter.
current.append(letter);
// Process the next digit.
backtrack(digits, index + 1, current, result, mapping);
// Undo the choice.
current.deleteCharAt(current.length() - 1);
}
}
Complexity
Each digit can map to at most 4 letters. Therefore, forn digits, the algorithm can generate up to 4n combinations. Since each combination contains n characters, the time complexity is O(n × 4n).
The recursion depth is
O(n), and the current combination requires O(n) space, excluding the space required for storing the output.
Comments
No comments yet. Ask a question or share what helped.