InterviewPrepKit

Home / Coding / Backtracking

Letter Combinations of a Phone Number

medium Original β†—
Solving tips
  • Recognize this as a pure Cartesian product with zero pruning: the recursion tree's leaves ARE the answer set, one letter per digit.
  • DFS on the digit index with append/recurse/pop keeps only O(n) working memory versus materializing all prefixes; itertools.product is the one-liner equivalent.
  • Guard empty input up front to return [] (not ['']), and remember 7 and 9 map to four letters, not three.
  • Time is O(4^n * n) since the output itself is that large, so every correct approach is asymptotically optimal; extra space is just O(n).

Problem

On an old phone keypad each digit from 2 to 9 maps to a group of letters: 2 β†’ abc, 3 β†’ def, 4 β†’ ghi, 5 β†’ jkl, 6 β†’ mno, 7 β†’ pqrs, 8 β†’ tuv, 9 β†’ wxyz (1 and 0 map to nothing). Given a string digits containing only characters 2–9, return every string that can be formed by picking one letter for each digit, in the digits’ order. Return them in any order. If digits is empty, return an empty list.

Examples

  • digits = "23" β†’ ["ad","ae","af","bd","be","bf","cd","ce","cf"] β€” 3 letters for 2 Γ— 3 letters for 3 = 9 strings.
  • digits = "" β†’ [] β€” no digits means no combinations (not [""]).
  • digits = "7" β†’ ["p","q","r","s"] β€” a single 4-letter digit.

Constraints

  • 0 <= len(digits) <= 4
  • digits[i] is a character in '2'..'9'

With at most 4 digits and at most 4 letters per digit, the output holds at most 4^4 = 256 strings β€” the output size is the running time, so every correct algorithm is asymptotically optimal; the exercise is structuring the generation cleanly.

Think about it first

Hint 1 The answer is a cross product: one letter from the first digit's group, one from the second's, and so on. How many results are there for "23"? For "234"?
Hint 2 Think of a tree: the root is the empty string, level i branches once per letter of digit i. The answers are exactly the leaves at depth len(digits). What traversal visits every leaf?
Hint 3 Recurse on the digit index: for each letter mapped to digits[i], append it to the current path, recurse to i + 1, then remove it. When i reaches len(digits), the path is one complete answer. An iterative version instead keeps a running list of prefixes and extends every prefix by every letter of the next digit.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.