Letter Combinations of a Phone Number
Difficulty: Medium · Pattern: Backtracking · LeetCode #17
Given a string of digits 2–9, return all letter combinations they could spell on a phone keypad (2 = abc, 3 = def, … 7 = pqrs, 9 = wxyz). Return them in the order of the keypad letters (lexicographic per digit).
Examples
text
"23" → ["ad","ae","af","bd","be","bf","cd","ce","cf"]
"" → []
"2" → ["a","b","c"]Hints
- The depth of the recursion is the index of the digit. The branching factor is that digit's 3 or 4 letters.
- Empty input returns
[], not[""].
Approach
This is a Cartesian product, built either with DFS (bt(i, path) appends each letter of digits[i]) or iteratively (res = [p + ch for p in res for ch in letters]). The output has up to 4ⁿ strings of length n, so O(n · 4ⁿ) is optimal.
Complexity
Time: O(n · 4ⁿ). Space: O(n) recursion besides the output.
Python solution
def letterCombinations(digits):
if not digits:
return []
keys = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
res = ['']
for d in digits:
res = [p + ch for p in res for ch in keys[d]]
return resJavaScript solution
function letterCombinations(digits) {
if (!digits) return [];
const keys = { 2: 'abc', 3: 'def', 4: 'ghi', 5: 'jkl', 6: 'mno', 7: 'pqrs', 8: 'tuv', 9: 'wxyz' };
const res = [];
const bt = (i, path) => {
if (i === digits.length) { res.push(path); return; }
for (const ch of keys[digits[i]]) bt(i + 1, path + ch);
};
bt(0, '');
return res;
}