Letter Combinations of a Phone Number

medium

Given a string digits containing digits from 2 to 9, return all the letter combinations the number could spell — one letter chosen for each digit, just like typing a word on an old phone keypad.

The keypad mapping is the classic one: 2 → abc, 3 → def, 4 → ghi, 5 → jkl, 6 → mno, 7 → pqrs, 8 → tuv, 9 → wxyz. The digits 0 and 1 map to no letters. You may return the combinations in any order.

Hints

Each digit offers only a handful of letters — what do you get when you combine one choice from every digit?
If you already had every combination for the first two digits, how would a third digit change that list?
Explore the choices depth-first: add a letter, recurse to the next digit, then remove it and try the next — classic backtracking.

Common doubts

An empty list. With no digits there are no choices to make, so there are zero combinations — not one empty string.
No. The constraints keep digits in the range 2 to 9, and 0 and 1 map to no letters anyway.
No — any order is accepted, so build the combinations in whatever order is simplest for your approach.

Interview follow-ups

Decide a policy up front: usually they contribute nothing, so you skip them; alternatively map them to a placeholder. Confirm the expected behavior with the interviewer.
Use mixed-radix indexing: at each position pick the letter by dividing and modding k against the product of the remaining digits' letter counts — O(n) time, no full enumeration.

Fun facts

  • This is many people's first encounter with backtracking — the same choose/explore/undo skeleton powers subsets, permutations, N-Queens, and Sudoku solvers.
  • The result count is exactly the product of each digit's letter count, so digits 7 and 9 (four letters each) blow the total up the fastest.

Asked at

AmazonGoogleMetaMicrosoftAppleBloomberg
Frequently Sometimes Occasionally
Example 1
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Digit 2 offers a, b, c and digit 3 offers d, e, f; pairing every choice gives nine words.
Example 2
Input: digits = "2"
Output: ["a","b","c"]
Constraints

- 1 <= digits.length <= 4 - digits[i] is a digit in the range ['2', '9'].

Solve this problem →