Letter Combinations of a Phone Number (LeetCode 17): Solution and Explanation

Medium
Hash Table
String
Backtracking

Each digit from 2 to 9 maps to a few letters, like on an old phone keypad. Given a string of such digits, return every word you could form by picking one letter for each digit, in order. An empty input gives an empty list.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

If you knew the input always had exactly two digits, you would write two nested loops: for each letter of the first digit, for each letter of the second digit, emit the pair. Three digits would need three loops. The problem is that the number of digits is only known at runtime, so you cannot hard-code the nesting depth.

Recursion is exactly the tool for a variable number of nested loops. Each recursive call handles one digit: it loops over that digit's letters, appends one to the string built so far, and calls itself for the next digit. When the string is as long as the input, every digit has contributed a letter, so it is a complete combination.

It helps to picture the result as a tree. The root is the empty string, the first level branches on the letters for the first digit, the second level on the letters for the second digit, and so on. Every leaf is one answer. There is no pruning here because every path is valid; the work is simply to visit every leaf.

The reference code builds the string immutably with curStr + c, so there is nothing to undo after the recursive call returns. It also guards the empty input case by only starting the recursion when digits is non-empty, since otherwise the empty string would be returned as a combination.

Approach: Backtracking over digit choices

  1. Build digitToChar, the mapping from each digit 2 to 9 to its letters, such as 7 to pqrs and 9 to wxyz.
  2. Define backtrack(i, curStr). If len(curStr) == len(digits), append curStr to res and return.
  3. Otherwise loop over every letter c in digitToChar[digits[i]].
  4. For each letter, call backtrack(i + 1, curStr + c) to fill in the remaining digits.
  5. Only start with backtrack(0, "") when digits is non-empty, then return res.

Step-by-step example

digits = "23"
  1. Digit 2 maps to abc and digit 3 maps to def. Start with backtrack(0, "").
  2. At index 0, pick a and call backtrack(1, "a"). At index 1, loop over d, e and f, producing ad, ae and af, each of length 2, so all three are recorded.
  3. Back at index 0, pick b and do the same, recording bd, be and bf.
  4. Pick c and record cd, ce and cf.
  5. The result is [ad, ae, af, bd, be, bf, cd, ce, cf], which is 3 × 3 = 9 combinations.

Code: Python, Java, C++

1class Solution:
2    def letterCombinations(self, digits: str) -> List[str]:
3        res = []
4        digitToChar = {
5            "2": "abc", "3": "def", "4": "ghi", "5": "jkl",
6            "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"
7        }
8        
9        def backtrack(i, curStr):
10            if len(curStr) == len(digits):
11                res.append(curStr)
12                return
13            
14            for c in digitToChar[digits[i]]:
15                backtrack(i + 1, curStr + c)
16                
17        if digits:
18            backtrack(0, "")
19        return res

Time and space complexity

Time

O(n × 4^n)

Each digit maps to at most four letters (7 and 9), so there are at most 4^n combinations for n digits. Building each string of length n by concatenation costs O(n).

Space

O(n)

The recursion depth is n and each frame holds a string of at most n characters, ignoring the output list itself.

Other approaches

Iterative breadth-first expansion (time O(n × 4^n), space O(n × 4^n))

Start with a list containing the empty string. For each digit, replace the list with every existing string extended by each of that digit's letters. It avoids recursion and is easy to follow, but it keeps a full level of partial strings in memory at once.

Cartesian product (time O(n × 4^n), space O(n × 4^n))

Collect the letter groups for each digit and take their Cartesian product, which in Python is itertools.product. It is concise but hides the reasoning interviewers usually want to see.

Common mistakes

  • Returning [""] for empty input. The recursion's base case fires immediately on an empty string, so you must guard the call when digits is empty.
  • Assuming every digit has three letters. Both 7 and 9 have four, which is why the bound is 4^n and not 3^n.
  • Using a mutable list for the current path and forgetting to pop after the recursive call, which makes combinations grow past the input length.
  • Indexing the mapping with an integer while digits contains characters, or the reverse, which leads to missing key errors.

Frequently asked questions

What is the time complexity of Letter Combinations of a Phone Number?

It is O(n × 4^n), where n is the number of digits. There are up to 4^n combinations because some digits have four letters, and each combination takes O(n) to build.

Can you solve it without recursion?

Yes. Start with a list holding an empty string and, for each digit, expand every string in the list by each letter of that digit. The result is the same set of combinations.

Why is this considered a backtracking problem?

The solution makes one choice per position, recurses to fill the rest, and then moves on to the next choice at the same level. That choose, explore, move on pattern is backtracking, even though no branch is ever pruned.

What should the function return for an empty string?

It should return an empty list rather than a list containing an empty string. The reference code handles this by only starting the recursion when digits is non-empty.