Letter Combinations of a Phone Number (LeetCode 17): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Build
digitToChar, the mapping from each digit 2 to 9 to its letters, such as 7 to pqrs and 9 to wxyz. - Define
backtrack(i, curStr). Iflen(curStr) == len(digits), appendcurStrtoresand return. - Otherwise loop over every letter
cindigitToChar[digits[i]]. - For each letter, call
backtrack(i + 1, curStr + c)to fill in the remaining digits. - Only start with
backtrack(0, "")whendigitsis non-empty, then returnres.
Step-by-step example
digits = "23"
- Digit 2 maps to abc and digit 3 maps to def. Start with
backtrack(0, ""). - 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. - Back at index 0, pick b and do the same, recording bd, be and bf.
- Pick c and record cd, ce and cf.
- 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 res1class Solution {
2 public List<String> letterCombinations(String digits) {
3 List<String> res = new ArrayList<>();
4 if (digits.length() == 0) return res;
5
6 String[] mapping = {
7 "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
8 };
9
10 backtrack(0, "", digits, mapping, res);
11 return res;
12 }
13
14 private void backtrack(int i, String curStr, String digits, String[] mapping, List<String> res) {
15 if (curStr.length() == digits.length()) {
16 res.add(curStr);
17 return;
18 }
19
20 String letters = mapping[digits.charAt(i) - '0'];
21 for (char c : letters.toCharArray()) {
22 backtrack(i + 1, curStr + c, digits, mapping, res);
23 }
24 }
25}1class Solution {
2public:
3 vector<string> letterCombinations(string digits) {
4 vector<string> res;
5 if (digits.empty()) return res;
6
7 string mapping[] = {
8 "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
9 };
10
11 backtrack(0, "", digits, mapping, res);
12 return res;
13 }
14
15 void backtrack(int i, string curStr, string digits, string mapping[], vector<string>& res) {
16 if (curStr.size() == digits.size()) {
17 res.push_back(curStr);
18 return;
19 }
20
21 string letters = mapping[digits[i] - '0'];
22 for (char c : letters) {
23 backtrack(i + 1, curStr + c, digits, mapping, res);
24 }
25 }
26};Time and space complexity
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).
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
digitsis 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
digitscontains 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.