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
Hiring now
Flexport has 115 open roles right now
landed applies to roles like these for you, on each company’s own site, with answers written for the role.
Software Engineer II, Autonomous Freight Technology
Bellevue, Washington, United States
Software Engineer II, DevEx
Amsterdam, Netherlands
Staff Software Engineer, DevEx
Amsterdam, Netherlands
Next question