Letter Combinations of a Phone Number

Medium#17letter by letter

On an old phone keypad each digit from 2 to 9 stands for three or four letters. You get a string of such digits; return every word you can type with it, one letter per digit, in any order, and nothing for an empty string. Our example: "38", where 3 is d, e, f and 8 is t, u, v, gives 9 words: dt, du, dv, et, eu, ev, ft, fu, fv.

phone keypad
1—2abc3def
4ghi5jkl6mno
7pqrs8tuv9wxyz
1 and 0 have no letters
17 Letter Combinations of a Phone NumberWalkthrough · 1×

Example: every word typed by "38". Watch the step after dv is saved: d is removed, and e takes its first place for the next three words.

[ ]ddtdudveeteuevfftfufv3→def8→tuvpath—results—
not reached yeton the way here; letter in the paththis stepsaved wordfinished or just removed

Spell every word the keys 38 can type; LETTERS gives each digit its letters

01/90
restart · back · play · step
Speed
1LETTERS = {"2": "abc", "3": "def", "4": "ghi",
2 "5": "jkl", "6": "mno", "7": "pqrs",
3 "8": "tuv", "9": "wxyz"}
4
5function letterCombinations(digits):
6 if digits is empty: return []
7 path = []
8 results = []
9 pickLetter(digits, 0, path, results)
10 return results
11
12function pickLetter(digits, i, path, results):
13 if i == len(digits):
14 results.add(join(path))
15 return
16 for letter in LETTERS[digits[i]]:
17 path.add(letter)
18 pickLetter(digits, i + 1, path, results)
19 path.removeLast()
state
digits
"38"
i
–
letter
–
path
–
results
–
click a step to go back

← → step · space play/pause

Why it works

  1. pickLetter with i chooses the letter for digits[i] and hands the rest to the call with i + 1, so the tree has one level per digit and one branch per letter: every word is one path from the root to a leaf.
  2. Removing the letter after the call comes back frees its place, so the next letter of the same digit is tried with the same letters before it.
  3. A word is saved only when i reaches the end, so it always has exactly one letter per digit.

Complexity

Time O(n × 4ⁿ) for n digits: up to 4ⁿ words, each joined in n steps. Memory O(n) besides the answer: the path and the call stack are n deep.

nextNow solve it yourself, no hints.

Solve it here →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.