All problems
0031MediumHash TableStringBacktracking

Keypad Code Spellings

Tracked in this browser only
Write code

Trains the technique from

LeetCode 17Letter Combinations of a Phone Number

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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