Letter Combinations of a Phone Number
Pattern: Recursion trees
Each digit stands for a few letters. Walk the digits left to right, branching once for every letter of the current digit. Every path to the end spells one combination.
The problem
Given a string of digits from 2 to 9, return every letter string the digits could stand for on a phone keypad (2 is
abc, 3 is def, 4 is ghi, 5 is jkl, 6 is mno, 7 is pqrs, 8 is tuv, 9 is wxyz). For example, "23" gives
ad ae af bd be bf cd ce cf. An empty input gives no combinations.
The function name letterCombinations matches LeetCode. Use the link above for the exact statement and limits. The
tests compare the answers after sorting.
Think first
- How many letters does each digit offer?
- How many combinations do
kdigits give? - What should the empty string return?
Hints
Brute force, and why it fails
There is nothing smaller: the output has up to 4^k strings, and each is built once. A loop that grows a list of
partial strings digit by digit is the same work without recursion.
The key insight
Every combination is one path through a tree whose levels are the digits and whose branches are that digit's letters.
Dry run
digits = 23. The key 2 has a b c, and the key 3 has d e f.
The plan
if digits is empty: return []
function build(i, cur):
if i == len(digits): record cur; return
for letter in KEYS[digits[i]]:
build(i + 1, cur + letter)
build(0, "")
Complexity
- Time
O(4^k × k)- Space
O(k)
Up to 4 letters per digit for k digits, each answer k characters long. The recursion is k deep.
Edge cases
- Empty input: no combinations (not one empty string).
- One digit: its letters.
- Digits 7 and 9 have four letters.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
private static final String[] KEYS = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits) {
List<String> out = new ArrayList<>();
if (!digits.isEmpty()) build(digits, 0, new StringBuilder(), out);
return out;
}
private void build(String digits, int i, StringBuilder cur, List<String> out) {
if (i == digits.length()) { out.add(cur.toString()); return; }
for (char c : KEYS[digits.charAt(i) - '0'].toCharArray()) { // one branch per letter on this key
cur.append(c);
build(digits, i + 1, cur, out);
cur.deleteCharAt(cur.length() - 1);
}
}
}C++
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> out;
if (!digits.empty()) { string cur; build(digits, 0, cur, out); }
return out;
}
void build(const string& digits, size_t i, string& cur, vector<string>& out) {
static const string KEYS[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
if (i == digits.size()) { out.push_back(cur); return; }
for (char c : KEYS[digits[i] - '0']) { // one branch per letter on this key
cur.push_back(c);
build(digits, i + 1, cur, out);
cur.pop_back();
}
}
};Python
class Solution:
KEYS = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
def letterCombinations(self, digits: str) -> list[str]:
out = []
def build(i: int, cur: list) -> None:
if i == len(digits):
out.append("".join(cur))
return
for c in self.KEYS[int(digits[i])]: # one branch per letter on this key
cur.append(c)
build(i + 1, cur)
cur.pop()
if digits:
build(0, [])
return outCommon mistakes
- Returning
[""]for an empty input. - Giving 7 or 9 only three letters.
- Building strings with
+in a deep Java loop instead of one shared builder.