Letter Combinations

35 min · letterCombinations()

One short number can hide a surprising number of words. The digits 23, for example, can start with any letter on 2 and finish with any letter on 3.

Given a string digits, return every letter string it can spell on this phone keypad:

  • 2 → abc, 3 → def, 4 → ghi, 5 → jkl
  • 6 → mno, 7 → pqrs, 8 → tuv, 9 → wxyz

Choose exactly one letter for each digit, and keep the digit order. You may return the finished strings in any order. When digits is empty, return [].

Constraints

  • 0 <= digits.length <= 7
  • Every character in digits is one of 2 through 9.

Hints

Build one layer at a time

Start with the choices for the first digit. For each later digit, append each of its letters to every partial string you already have.

Think in decisions

At position i, your only decision is which letter mapped from digits[i] comes next. Once you choose it, move to position i + 1.

Undo after exploring

Add one letter to the current path, explore everything below that choice, then remove it before trying the next letter. The empty input needs an early return so it produces [], not a list containing one empty string.

Follow-up

Could you write the search so it stores only the current path, apart from the strings that must be returned?

Visible cases

Examples

Example 1

ready
Input
digits = "23"
Expected
[
  "ad",
  "ae",
  "af",
  "bd",
  "be",
  "bf",
  "cd",
  "ce",
  "cf"
]
Why
three choices from 2 combine with three choices from 3

Example 2

ready
Input
digits = ""
Expected
[]
Why
no digits means there is no letter string to build

Example 3

ready
Input
digits = "7"
Expected
[
  "p",
  "q",
  "r",
  "s"
]
Why
7 maps to four letters

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite