InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Backtracking

Letter Combinations of a Phone Number

medium Original ↗ 00:00

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 29, 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 equals the running time, so every correct algorithm is asymptotically optimal; the exercise is generating the combinations 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug