Show problems as
Classic problem #17MediumHash TableStringBacktracking

Letter Combinations of a Phone Number

Real-world version: Keypad Code Spellings
Tracked in this browser only
Read Letter Combinations of a Phone Number on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstBacktracking · Recursion, animated step by step

A parcel locker is opened with a word, but its keypad is the old telephone kind: every key from 2 to 9 carries a small group of lowercase letters, and the keys 0 and 1 carry none.

2 -> a b c      6 -> m n o
3 -> d e f      7 -> p q r s
4 -> g h i      8 -> t u v
5 -> j k l      9 -> w x y z

A courier watched a customer press the keys but could not see which letter on each key was intended. Given the pressed sequence as a string code, list every word that could have been meant, taking exactly one letter from the group of each key, in the order the keys were pressed.

You may list the words in whatever order you like. When code is empty nothing was pressed, so the answer is an empty list.

Examples

Example 1

Input
code = "79"
Output
["pw", "px", "py", "pz", "qw", "qx", "qy", "qz", "rw", "rx", "ry", "rz", "sw", "sx", "sy", "sz"]

Key 7 offers four letters and key 9 offers four, giving 4 * 4 = 16 candidate words.

Example 2

Input
code = "94"
Output
["wg", "wh", "wi", "xg", "xh", "xi", "yg", "yh", "yi", "zg", "zh", "zi"]

Four letters on key 9 pair with three on key 4, so twelve words fit the sequence.

Example 3

Input
code = "4"
Output
["g", "h", "i"]

One key was pressed, so each of its three letters is a candidate on its own.

Constraints

  • 0 <= code.length <= 4
  • Every character of code is a digit from '2' through '9'.

The groups you return, and the values inside each group, may be in any order.

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def keypad_spellings(code: str) -> list[str]:
Java
public List<String> keypadSpellings(String code)