LeetCode #17 Medium

Letter Combinations of a Phone Number

Letter Combinations of a Phone Number is LeetCode 17 (Medium). You get a string digits made of the characters 2 to 9. Return every string you could type by pressing one letter on each of those keys of an old phone keypad, in the order the digits appear.

  • Keys 2 to 6 and 8 carry three letters; 7 (pqrs) and 9 (wxyz) carry four.
  • The answer may be returned in any order.

The string has at most 4 digits, so there are at most 4 × 4 × 4 × 4 = 256 strings, and listing every one of them is the whole job.

Constraints
  • 1 <= digits.length <= 4
  • digits[i] is a digit in the range ['2', '9'].
backtrackingstringrecursionhash-table
Open on LeetCode ↗
02

Intuition

You need one letter from each key, in order. With two digits that is two nested loops; with four it is four. But the number of digits is only known when the code runs, so the loops cannot be written out by hand.

Recursion gives you one loop per digit. The call for position i loops over the letters of digits[i], adds one letter to the string being built, and calls itself for position i + 1. When i reaches the end, the string has exactly one letter per digit, so it is finished. Removing the letter after the call returns lets the next letter of the same key start from the same prefix.

How to spot this pattern

"Pick one item from each group, in order, and list every way to do it" is a product of choices. Backtracking with one recursion level per group lists them without knowing the number of groups in advance.

03

Approach

Try it first

Before reading on, write the two-digit version with nested loops, then ask what one level of that loop nest would look like as a function that calls itself. Aim for O(n · 4ⁿ) time.

1

Store the keypad

Hard-code a map from each digit '2' to '9' to its letters. The keypad never changes, so there is nothing to compute. Check the two four-letter keys by eye: 7 is pqrs and 9 is wxyz.

2

Handle one digit per call

backtrack(i) loops over the letters of digits[i]. For each letter, append it to path, call backtrack(i + 1) to fill the remaining positions, then pop it, so the next letter of the same key is tried on the same prefix.

3

Record a full path

When i == len(digits), every digit has added exactly one letter, so join path into a string and add it to the answer. No length check is needed, because the depth of the call is the length of the path.

4

Start at the first digit

Call backtrack(0) once and return the collected list. Letters are tried in keypad order at every level, so the answer comes out sorted: for "23" it starts with "ad", "ae", "af".

04

Code in Python, C++ and Java

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def letterCombinations(self, digits: str) -> List[str]:
▶6 if not digits:
▶7 return []
▶8 pad = {
▶9 "2": "abc", "3": "def", "4": "ghi", "5": "jkl",
▶10 "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz",
▶11 }
▶12 res, path = [], []
▶13 
▶14 def backtrack(i):
▶15 if i == len(digits):
▶16 res.append("".join(path))
▶17 return
▶18 for ch in pad[digits[i]]:
▶19 path.append(ch)
▶20 backtrack(i + 1)
▶21 path.pop()
▶22 
▶23 backtrack(0)
▶24 return res
key 2abckey 3defpathfound 0 of 92 keys → 3 × 3 = 9 strings to find
digits"23"
res[]
Each string takes one letter from every key, in order. That is 3 × 3 = 9 strings, so 9 empty slots wait to be filled. backtrack(0) starts at position 0.
key 2abcposition 0key 3defpathafound 0 of 9position 0: take a from key 2 → go deeper
path"a"
Put a in position 0 and call the next level, which loops over key 3. Every string that begins with "a" is built down there.
key 2abckey 3defposition 1pathadfound 1 of 9adtake d → "ad" is complete → record it
path"ad"
found1 of 9
Taking d fills the last position, so "ad" has one letter from every key. It is recorded, and the letter is removed again when the call returns.
key 2abckey 3defposition 1pathaefound 2 of 9adaetake e → "ae" is complete → record it
path"ae"
found2 of 9
Undo d and try the next letter of key 3. Taking e fills the last position, so "ae" has one letter from every key. It is recorded, and the letter is removed again when the call returns.
key 2abckey 3defposition 1pathaffound 3 of 9adaeaftake f → "af" is complete → record it
path"af"
found3 of 9
Undo e and try the next letter of key 3. Taking f fills the last position, so "af" has one letter from every key. It is recorded, and the letter is removed again when the call returns.
key 2abcposition 0key 3defpathbfound 3 of 9adaeafposition 0: take b from key 2 → go deeper
path"b"
Every string starting with a is found, so a is popped. Put b in position 0 and call the next level, which loops over key 3. Every string that begins with "b" is built down there.
key 2abckey 3defposition 1pathbdfound 4 of 9adaeafbdtake d → "bd" is complete → record it
path"bd"
found4 of 9
Taking d fills the last position, so "bd" has one letter from every key. It is recorded, and the letter is removed again when the call returns.
key 2abckey 3defposition 1pathbefound 5 of 9adaeafbdbetake e → "be" is complete → record it
path"be"
found5 of 9
Undo d and try the next letter of key 3. Taking e fills the last position, so "be" has one letter from every key. It is recorded, and the letter is removed again when the call returns.
key 2abckey 3defposition 1pathbffound 6 of 9adaeafbdbebftake f → "bf" is complete → record it
path"bf"
found6 of 9
Undo e and try the next letter of key 3. Taking f fills the last position, so "bf" has one letter from every key. It is recorded, and the letter is removed again when the call returns.
key 2abcposition 0key 3defpathcfound 6 of 9adaeafbdbebfposition 0: take c from key 2 → go deeper
path"c"
Every string starting with b is found, so b is popped. Put c in position 0 and call the next level, which loops over key 3. Every string that begins with "c" is built down there.
key 2abckey 3defposition 1pathcdfound 7 of 9adaeafbdbebfcdtake d → "cd" is complete → record it
path"cd"
found7 of 9
Taking d fills the last position, so "cd" has one letter from every key. It is recorded, and the letter is removed again when the call returns.
key 2abckey 3defposition 1pathcefound 8 of 9adaeafbdbebfcdcetake e → "ce" is complete → record it
path"ce"
found8 of 9
Undo d and try the next letter of key 3. Taking e fills the last position, so "ce" has one letter from every key. It is recorded, and the letter is removed again when the call returns.
key 2abckey 3defposition 1pathcffound 9 of 9adaeafbdbebfcdcecftake f → "cf" is complete → record it
path"cf"
found9 of 9
Undo e and try the next letter of key 3. Taking f fills the last position, so "cf" has one letter from every key. It is recorded, and the letter is removed again when the call returns.
key 2abckey 3defpathfound 9 of 9adaeafbdbebfcdcecfall 9 found → return them
len(res)9
Every letter of the first key has been tried and undone, so the path is empty again and all 9 slots are filled. They came out in keypad order because each level tries its letters left to right.
05

Build level by level

Keep the list of every prefix built so far. Each digit replaces that list with every prefix followed by every letter of the key, so after the last digit the list holds the answer. Build a new list each round instead of appending to the one you are reading.

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def letterCombinations(self, digits: str) -> List[str]:
▶6 if not digits:
▶7 return []
▶8 pad = {
▶9 "2": "abc", "3": "def", "4": "ghi", "5": "jkl",
▶10 "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz",
▶11 }
▶12 res = [""]
▶13 for d in digits:
▶14 res = [prefix + ch for prefix in res for ch in pad[d]]
▶15 return res
06

Common pitfalls

Forgetting to remove the letter

✗ Wrong
for ch in pad[digits[i]]:
    path.append(ch)
    backtrack(i + 1)
✓ Right
for ch in pad[digits[i]]:
    path.append(ch)
    backtrack(i + 1)
    path.pop()

Without the pop, letters pile up across siblings. For "23" the answer starts "ad", "ade", "adef" instead of "ad", "ae", "af", because each new letter is added after the previous one instead of replacing it.

Indexing the keypad array without the two empty slots

✗ Wrong
pad = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
... pad[digits[i] - '0']
✓ Right
pad = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
... pad[digits[i] - '0']

Digit 2 then reads slot 2, which is ghi, so every key is shifted by two, and digits 8 and 9 read past the end of the array. Either keep slots 0 and 1 empty or subtract 2 from the digit.

07

Edge cases

A single digit such as "2"

The recursion goes one level deep and returns the key's letters one by one: ["a", "b", "c"].

Repeated digits such as "22"

Each position picks from the same key independently, so "aa", "ab" and "ba" are all separate answers, 9 in total.

08

Complexity

Time
O(n · 4ⁿ)
Space
O(n)
n is the number of digits. There are at most 4ⁿ strings and joining each one costs O(n). Apart from the output list, memory is the path and the call stack, both n deep.
09

Letter Combinations of a Phone Number FAQ

Why is the bound 4ⁿ and not 3ⁿ?

Keys 7 and 9 have four letters. The exact count is the product of the letter counts of the keys pressed: "23" gives 3 × 3 = 9 strings and "79" gives 4 × 4 = 16. Only when every digit is 7 or 9 does it reach 4ⁿ.

What should an empty string return?

An empty list []. The current constraints guarantee at least one digit, but older versions of the problem tested "". Without the guard, backtrack(0) is already at the end and records one empty string, so the answer becomes [""].