Letter Combinations of a Phone Number

Cartesian product of digit-to-letters mappings via DFS.

Medium
Time O(4^n * n) Space O(n)
LeetCode
3 min read
subsets backtracking string

Problem#

Given a string of digits 2–9, return all possible letter combinations from the phone-keypad mapping (2 → abc, 3 → def, …).

Examples#

  • "23"["ad","ae","af","bd","be","bf","cd","ce","cf"]

Constraints#

  • 0 <= digits.length <= 4.

Approach#

DFS with a path accumulator. At each depth, iterate the digit’s letters, push, recurse, pop.

Solution#

Letter Combinations of a Phone Number
class Solution {
public:
vector<string> letterCombinations(string digits) {
if (digits.empty()) return {};
const vector<string> M = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
vector<string> out;
string path;
function<void(int)> dfs = [&](int i){
if (i == (int)digits.size()) { out.push_back(path); return; }
for (char c : M[digits[i] - '0']) {
path.push_back(c);
dfs(i + 1);
path.pop_back();
}
};
dfs(0);
return out;
}
};

Editorial#

The product space is Π |letters(digit)|. DFS lets us emit each combination on leaf hit without materializing intermediate products. The push/pop pattern is the canonical backtracking unwind.

Complexity#

  • Time: O(4^n * n).
  • Space: O(n) recursion + O(4^n * n) output.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.