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.
- 1 <= digits.length <= 4
- digits[i] is a digit in the range ['2', '9'].
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.
"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.
Approach
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.
Two ways to solve it
One recursion level per digit: add a letter, go deeper, take it back.
- Memory: one path of length n besides the output.
- Pattern: the same shape as subsets, permutations and combination sum.
The usual interview answer.
Start from [""] and, for each digit, extend every string so far by each of its letters.
- No recursion: a loop and a list.
- Cost: keeps a whole level of partial strings at once.
Short to write once the idea is clear.
Both list the same strings in O(n · 4ⁿ) time. Backtracking is shown first because it keeps only one string in progress; the level-by-level version comes after the demo.
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.
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.
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.
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".
Code in Python, C++ and Java
backtrack(0) starts at position 0.backtrack(0) starts at position 0.backtrack(0) starts at position 0.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.
Common pitfalls
Forgetting to remove the letter
for ch in pad[digits[i]]:
path.append(ch)
backtrack(i + 1)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
pad = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
... pad[digits[i] - '0']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.
Edge cases
The recursion goes one level deep and returns the key's letters one by one: ["a", "b", "c"].
Each position picks from the same key independently, so "aa", "ab" and "ba" are all separate answers, 9 in total.
Complexity
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 [""].