Phone Letter CombinationsLoading saved progress…

Phone Letter Combinations

Letter Combinations of a Phone Number (LeetCode 17) asks you to list every letter string a sequence of keypad digits could spell. On the classic phone keypad each digit from 2 to 9 prints a few letters — 2 is abc, 3 is def, 4 is ghi, and so on up to 9 (wxyz) — the same layout that once let you type words on a number pad. Given a digit string you return every combination formed by choosing one letter for each digit, so 23 produces the nine strings ad, ae, af, bd, be, bf, cd, ce, cf. Most digits map to three letters, but 7 (pqrs) and 9 (wxyz) map to four, and 0 and 1 map to none.

Signature

phoneLetterCombos(digits)  // a string of keypad digits -> an array of letter strings

Examples

phoneLetterCombos("23");
// ["ad","ae","af","bd","be","bf","cd","ce","cf"]  (9 combinations, any order)

phoneLetterCombos("2");
// ["a","b","c"]

phoneLetterCombos("");
// []   (empty input -> empty array, not [""])

Notes

  • The keypad2abc, 3def, 4ghi, 5jkl, 6mno, 7pqrs, 8tuv, 9wxyz.
  • Four-letter keys7 and 9 each map to four letters; every other digit maps to three. Do not hard-code three letters per digit.
  • No letters0 and 1 print no letters and will not appear in the input, so you do not need to handle them.
  • Empty inputphoneLetterCombos("") returns [], an empty array — not [""], a list holding one empty string.
  • Order and count — return the combinations in any order; the tests compare them as sets. The number of combinations is the product of each digit's letter count, so 27 has 3 × 4 = 12.

FAQ

What does phoneLetterCombos of an empty string return?
An empty array. There are no digits to spell, so there are zero combinations — not one empty combination. Seeding a build with a list that already holds the empty string is the classic way to return a wrong one-element result here.
What is the time and space complexity?
Exponential in the number of digits. With d digits and up to four letters each, there are up to 4^d combinations, and every one is built and stored, so both the running time and the output size are O(4^d). You cannot do better when the task is to list them all, because the answer itself can be that large.
How is this different from generating permutations?
Permutations reorder one fixed set of items; here each position draws from its own set and nothing is reused or reordered. You pick exactly one letter from each digit's letters, in order, which makes it a cartesian product across the digits — so the count is the product of the per-digit letter counts, not a factorial.
Loading editor…