Letter Combinations of a Phone Number
The problem
Given a string consisting of digits from 2 to 9 (inclusive). Return all possible letter combinations that the number can represent.
Mapping of digits to letters is given in first example.
Input : digits = "34" Output : [ "dg", "dh", "di", "eg", "eh", "ei", "fg", "fh", "fi" ] Explanation : The 3 is mapped with "def" and 4 is mapped with "ghi". So all possible combination by replacing the digits with characters are shown in output.
Input : digits = "3" Output : [ "d", "e", "f" ] Explanation : The 3 is mapped with "def".
Input : digits = "8"
- 1 <= digits.length <= 4
- digts[i] contains digitd from [2,9].
cpp
class Solution {
public:
vector<string> letterCombinations(string digits) {
//your code goes here
}
};java
class Solution {
public List<String> letterCombinations(String digits) {
//your code goes here
}
}python
class Solution:
def letterCombinations(self, digits):
#your code goes herejavascript
class Solution {
letterCombinations(digits) {
//your code goes here
}
}csharp
public class Solution
{
public IList<string> LetterCombinations(string digits)
{
//your code goes here
}
}go
func letterCombinations(digits string) []string {
//your code goes here
}Stuck? Show a way to structure it+
- 01Create the digit-to-letters lookup.
- 02Return an empty list for empty input.
- 03Append each mapped letter at a position.
- 04Recurse to the next digit and backtrack.
- 05Emit the path after all digits are consumed.
Reference answer
Then expect these follow-ups
How would you stream combinations instead of storing them?
Tests: constraint adaptation
How do you support a custom keypad mapping?
Tests: follow-up reasoning
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question