Letter Combinations of a Phone Number

Try to solve the Letter Combinations of a Phone Number problem.

Statement#

Given a string containing digits from 2 to 9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

The illustration below shows the mapping of digits to letters in a telephone dial pad.

Note: The number 11 on the telephone dial pad does not correspond to any letter, so the input string only contains digits from 22 to 99.

1
1
2
2
3
3
4
4
5
5
6
6
7
7
8
8
9
9
abc
abc
def
def
ghi
ghi
jkl
jkl
mno
mno
pqrs
pqrs
tuv
tuv
wxyz
wxyz
Viewer does not support full SVG 1.1

Constraints:

  • 00 \leq digits.length 4\leq 4

  • digits[i] is a digit in the range [2,9][2, 9]

Examples#

Created with Fabric.js 3.6.6 Input Sample example 1 ad ae af bd be bf cd ce cf Digits = 23

1 of 3

Created with Fabric.js 3.6.6 dg dh di eg eh ei fg fh fi Input Sample example 2 Digits = 34

2 of 3

Created with Fabric.js 3.6.6 p q r s Input Sample example 3 Digits = 7

3 of 3

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Letter Combinations of a Phone Number

1

What should be the output if the following digits are given as input?

Digits = 29

A)

[aw, ax, ay, az]

B)

[bw, bx, by, bz]

C)

[aw, ax, ay, az, bw, bx, by, bz, cw, cx, cy, cz]

D)

[cw, cx, cy, cz]

Question 1 of 40 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Initialize an empty list to store all the combinations.

If the input string of digits is empty, return an empty list, since there are no possible combinations.

Initialize a dictionary that maps the digits to their corresponding characters.

Check if the length of our current combination is the same as the length of the input, add it to the list of results and backtrack.

Otherwise, retrieve the list of possible letters corresponding to the digit at the current index and iterate through each letter to generate the combinations recursively.


Try it yourself#

Implement your solution in the following coding playground:

Python
usercode > main.py
Input #1
Letter Combinations of a Phone Number

Solution: Permutations

Solution: Letter Combinations of a Phone Number