Letter Combinations of a Phone Number

Asked atAmazonFlexport
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

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 here

javascript

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+
  1. 01Create the digit-to-letters lookup.
  2. 02Return an empty list for empty input.
  3. 03Append each mapped letter at a position.
  4. 04Recurse to the next digit and backtrack.
  5. 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.

Get 5x interviews10 free auto-applies. No card.
  • Software Engineer II, Autonomous Freight Technology

    Bellevue, Washington, United States

  • Software Engineer II, DevEx

    Amsterdam, Netherlands

  • Staff Software Engineer, DevEx

    Amsterdam, Netherlands

Or practice this question first

Next question