#17
Letter Combinations of a Phone Number
Medium Backtracking over choices
- Read
- Understand
- Hints
- Approach
- Solution
- Solved
?The problem
Each digit 2–9 maps to letters as on a phone keypad. Return all letter strings the digit string could represent.
This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗
◎Understanding
Really asking: every word the digits could spell on a phone keypad.
Why this works: one recursion level per digit, one branch per letter on that key.
Example: "23"
2 → a, b, c ; 3 → d, e, fad ae af bd be bf cd ce cf
✦Hints open one at a time
One recursion level per digit.
At each level loop over the letters of that digit.
↗Approach
Keep a StringBuilder path. At index i, for every letter of digits[i], append, recurse to i + 1, and delete the last character. Return an empty list for empty input.
</>Solution (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> res = new ArrayList<>();
if (digits.isEmpty()) return res;
backtrack(digits, 0, new StringBuilder(), res);
return res;
}
private void backtrack(String digits, int i, StringBuilder path, List<String> res) {
if (i == digits.length()) {
res.add(path.toString());
return;
}
for (char c : KEYS[digits.charAt(i) - '0'].toCharArray()) {
path.append(c);
backtrack(digits, i + 1, path, res);
path.deleteCharAt(path.length() - 1);
}
}
}
!Common mistake
Returning [""] for an empty input — the expected answer is an empty list.
Complexity
- Time: O(4^n · n).
- Space: O(n).
Topic: Recursion & Backtracking
🎬 Episodes 29–36: video coming soon