15% off all plans & roadmaps Use code
See plansLetter Combinations of a Phone Number
- LeetCode 17
- Medium
- Backtracking Patterns
- Subsets (Include/Exclude)
Updated
TL;DR: Turn a string of digits 2-9 into every letter string a phone keypad could spell. Backtracking picks one letter per digit, recurses to the next digit, then undoes the pick.
Problem
You are given a string digits that contains only the characters 2 through 9. Return every letter combination the number could spell on a telephone keypad. You may return the answer in any order.
The keypad maps digits to letters as shown below. The digit 1 maps to no letters.
| Digit | Letters |
|---|---|
| 2 | abc |
| 3 | def |
| 4 | ghi |
| 5 | jkl |
| 6 | mno |
| 7 | pqrs |
| 8 | tuv |
| 9 | wxyz |
Example 1
Input: digits = "23" Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2
Input: digits = "" Output: []
Example 3
Input: digits = "2" Output: ["a","b","c"]
Constraints
0 <= digits.length <= 4digits[i]is a digit in the range['2', '9'].
Constraints that matter
digits.length <= 4means at most 4 * 4 * 4 * 4 = 256 results. An exponential search is fine here, and the work is bounded by the output size.- Each digit maps to 3 or 4 letters, so the result count is the product of the letter counts. Your solution cannot beat the time needed to write that output.
digits.lengthcan be 0, and the expected answer is[], not['']. A naive recursion returns the empty string for empty input, so you must guard it.- Digits are only
2to9. You can index a fixed 10-slot table by the digit value and never check for0or1. - The length is tiny, so recursion depth is at most 4. Recursion is safe in every language, including Python.
Hints
Hint 1
This is a backtracking problem.
Hint 2
The most naive route ignores the structure of the keypad.
Solution
Intuition
This is a backtracking problem. You build a string one position at a time, and each position has a small fixed set of choices. Position i takes one letter from the keypad entry of digits[i].
Picture a row of combination dials, one per digit, where each dial only shows the letters on its key. The dial's setting is the letter in the path, and turning a dial back to its start is the undo step.
If the length were fixed at 2, you would write two nested loops. The length varies from 0 to 4, so you would need a different number of nested loops for each input. Recursion gives you that: the recursion depth plays the role of the loop level. Depth 0 loops over letters of the first digit, depth 1 loops over letters of the second, and so on.
The search forms a tree. The root is the empty string. Each node at depth i has one child per letter of digits[i]. Leaves sit at depth n and each one is a finished answer. Walking the tree depth first visits every leaf exactly once, so you get every combination with no duplicates.
The tool that keeps this cheap is undoing a choice after you explore it. You append a letter, recurse, then remove the letter and try the next one. One shared path buffer serves the whole search. The alternative is to expand layer by layer with a queue, which reaches the same answers with more memory.
Worked example
Input: digits = "279" Output: ["apw","apx","apy","apz","aqw","aqx","aqy","aqz","arw","arx","ary","arz","asw","asx","asy","asz","bpw","bpx","bpy","bpz","bqw","bqx","bqy","bqz","brw","brx","bry","brz","bsw","bsx","bsy","bsz","cpw","cpx","cpy","cpz","cqw","cqx","cqy","cqz","crw","crx","cry","crz","csw","csx","csy","csz"] Explanation: The digit 2 offers 3 letters (abc), 7 offers 4 (pqrs) and 9 offers 4 (wxyz). Every choice for one digit pairs with every choice for the others, so the answer has 3 * 4 * 4 = 48 strings. Each string is 3 letters long, one letter per digit, and the list above is in alphabetical order.
Approach 1: Brute force: filter every letter string
The most naive route ignores the structure of the keypad. The answer is made of strings of length n over the alphabet, so generate every string of n lowercase letters and keep the ones that match.
A string matches when its letter at position i appears in the keypad entry for digits[i]. You can enumerate all 26^n strings with a counter in base 26. Each counter value decodes to one string, and counting upward produces alphabetical order.
Steps
- If
digitsis empty, return an empty list. - Compute
total = 26^n, wherenis the length ofdigits. - Loop
codefrom 0 tototal - 1. - Decode
codeintonletters by taking remainders modulo 26, filling positions from the last to the first. - Check each position: the letter must belong to the keypad entry of the digit at that position.
- If every position passes, add the string to the result.
- Return the result.
Dry run
Take digits = "279", so n = 3 and total = 26^3 = 17576 strings.
code = 0decodes toaaa. Position 1 needs a letter frompqrs, andais not in it, so the string is rejected.- Most codes fail the same way. The first one to pass is
apw: a = 0, p = 15, w = 22, socode = 0 * 676 + 15 * 26 + 22 = 412. - Codes 413, 414 and 415 give
apx,apyandapz, which all pass. Code 416 isaqa, which fails on the third letter, and the scan rejects codes 416 to 437. - Code 438 is
aqw, the fifth accepted string. - The last accepted string is
cszat code2 * 676 + 18 * 26 + 25 = 1845. After that, codes up to 17575 all fail.
Exactly 48 of the 17576 strings pass, in alphabetical order, which matches the expected output.
Complexity
| Time | O(26^n * n) |
|---|---|
| Space | O(n) extra, plus the output |
Here n is the length of digits. The loop runs 26^n times, and each iteration spends O(n) to decode the code and O(n) to check positions. Extra space is one buffer of n characters, not counting the result list. For n up to 4 this is 456976 iterations, which runs, but it wastes almost all of them: only at most 256 strings are valid.
PythonTested in our runner
from typing import List, Optional
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []
keypad = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
n = len(digits)
result = []
for code in range(26 ** n):
chars = [""] * n
c = code
# decode the counter into n letters, last position first
for i in range(n - 1, -1, -1):
c, r = divmod(c, 26)
chars[i] = chr(97 + r)
# keep the string only if every letter fits its digit
if all(chars[i] in keypad[int(digits[i])] for i in range(n)):
result.append("".join(chars))
return result
JavaTested in our runner
import java.util.*;
class Solution {
private static final String[] KEYPAD = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public String[] letterCombinations(String digits) {
int n = digits.length();
if (n == 0) {
return new String[0];
}
int total = 1;
for (int i = 0; i < n; i++) {
total *= 26;
}
List<String> result = new ArrayList<>();
char[] buf = new char[n];
for (int code = 0; code < total; code++) {
int c = code;
// decode the counter into n letters, last position first
for (int i = n - 1; i >= 0; i--) {
buf[i] = (char) ('a' + c % 26);
c /= 26;
}
boolean ok = true;
for (int i = 0; i < n; i++) {
if (KEYPAD[digits.charAt(i) - '0'].indexOf(buf[i]) < 0) {
ok = false;
break;
}
}
if (ok) {
result.add(new String(buf));
}
}
return result.toArray(new String[0]);
}
}
C++Tested in our runner
using namespace std;
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> result;
int n = digits.size();
if (n == 0) {
return result;
}
const string keypad[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
int total = 1;
for (int i = 0; i < n; i++) {
total *= 26;
}
string buf(n, 'a');
for (int code = 0; code < total; code++) {
int c = code;
// decode the counter into n letters, last position first
for (int i = n - 1; i >= 0; i--) {
buf[i] = 'a' + c % 26;
c /= 26;
}
bool ok = true;
for (int i = 0; i < n; i++) {
if (keypad[digits[i] - '0'].find(buf[i]) == string::npos) {
ok = false;
break;
}
}
if (ok) {
result.push_back(buf);
}
}
return result;
}
};
JavaScriptTested in our runner
/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function(digits) {
const n = digits.length;
if (n === 0) {
return [];
}
const keypad = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];
let total = 1;
for (let i = 0; i < n; i++) {
total *= 26;
}
const result = [];
const buf = new Array(n);
for (let code = 0; code < total; code++) {
let c = code;
// decode the counter into n letters, last position first
for (let i = n - 1; i >= 0; i--) {
buf[i] = String.fromCharCode(97 + (c % 26));
c = Math.floor(c / 26);
}
let ok = true;
for (let i = 0; i < n; i++) {
if (!keypad[Number(digits[i])].includes(buf[i])) {
ok = false;
break;
}
}
if (ok) {
result.push(buf.join(""));
}
}
return result;
};
GoTested in our runner
import "strings"
func letterCombinations(digits string) []string {
n := len(digits)
result := []string{}
if n == 0 {
return result
}
keypad := [10]string{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
total := 1
for i := 0; i < n; i++ {
total *= 26
}
buf := make([]byte, n)
for code := 0; code < total; code++ {
c := code
// decode the counter into n letters, last position first
for i := n - 1; i >= 0; i-- {
buf[i] = byte('a' + c%26)
c /= 26
}
ok := true
for i := 0; i < n; i++ {
if strings.IndexByte(keypad[digits[i]-'0'], buf[i]) < 0 {
ok = false
break
}
}
if ok {
result = append(result, string(buf))
}
}
return result
}
C#Tested in our runner
public class Solution {
private static readonly string[] Keypad = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
public string[] letterCombinations(string digits) {
int n = digits.Length;
if (n == 0) {
return new string[0];
}
int total = 1;
for (int i = 0; i < n; i++) {
total *= 26;
}
var result = new List<string>();
char[] buf = new char[n];
for (int code = 0; code < total; code++) {
int c = code;
// decode the counter into n letters, last position first
for (int i = n - 1; i >= 0; i--) {
buf[i] = (char)('a' + c % 26);
c /= 26;
}
bool ok = true;
for (int i = 0; i < n; i++) {
if (Keypad[digits[i] - '0'].IndexOf(buf[i]) < 0) {
ok = false;
break;
}
}
if (ok) {
result.Add(new string(buf));
}
}
return result.ToArray();
}
}
Approach 2: Iterative queue expansion
What's slow: the brute force visits 26^n strings to find at most 4^n valid ones, and it throws away nearly every string it builds. It never uses the fact that each digit only allows 3 or 4 letters.
The insight that fixes it: build only valid strings. Keep a queue of prefixes that already match the first i digits. To handle digit i, take each prefix out of the queue and put back one longer prefix per letter of that digit. After the last digit, the queue holds the answer.
Steps
- If
digitsis empty, return an empty list. - Create a queue that holds one item, the empty string.
- For each digit, read the current queue size
s. - Repeat
stimes: remove the front prefix. - For each letter mapped to the digit, append the letter to the prefix and push the new string to the back.
- After the last digit, every string in the queue has length
n. - Return the queue contents in order.
Dry run
Take digits = "279".
| Digit | Queue before | Work | Queue size after |
|---|---|---|---|
| start | [""] | none | 1 |
| 2 | [""] | pop "", push a, b, c | 3 |
| 7 | [a, b, c] | pop a, push ap, aq, ar, as. Then the same for b and c. | 12 |
| 9 | [ap, aq, ..., cs] | pop ap, push apw, apx, apy, apz. Repeat for all 12 prefixes. | 48 |
Because the queue is first in, first out and each prefix is expanded in letter order, the order stays alphabetical. The front of the final queue is apw and the back is csz, which gives the 48 expected strings.
Complexity
| Time | O(n * 4^n) |
|---|---|
| Space | O(n * 4^n) |
Here n is the length of digits. A digit has at most 4 letters, so the queue holds at most 4^i strings after i digits, and each push builds a string of length up to n, so layer i costs O(i * 4^i). The last layer dominates, giving O(n * 4^n) time. Space is also O(n * 4^n) because the queue stores the whole current layer next to the next one, so it matches the output size but keeps intermediate layers in memory too.
PythonTested in our runner
from typing import List, Optional
from collections import deque
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []
keypad = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
queue = deque([""])
for d in digits:
# expand exactly the prefixes that belong to the current layer
for _ in range(len(queue)):
prefix = queue.popleft()
for ch in keypad[int(d)]:
queue.append(prefix + ch)
return list(queue)
JavaTested in our runner
import java.util.*;
class Solution {
private static final String[] KEYPAD = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public String[] letterCombinations(String digits) {
if (digits.length() == 0) {
return new String[0];
}
Queue<String> queue = new ArrayDeque<>();
queue.add("");
for (int i = 0; i < digits.length(); i++) {
String letters = KEYPAD[digits.charAt(i) - '0'];
// expand exactly the prefixes that belong to the current layer
int size = queue.size();
for (int k = 0; k < size; k++) {
String prefix = queue.poll();
for (int j = 0; j < letters.length(); j++) {
queue.add(prefix + letters.charAt(j));
}
}
}
return queue.toArray(new String[0]);
}
}
C++Tested in our runner
using namespace std;
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> result;
if (digits.empty()) {
return result;
}
const string keypad[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
queue<string> q;
q.push("");
for (char d : digits) {
// expand exactly the prefixes that belong to the current layer
int size = q.size();
for (int k = 0; k < size; k++) {
string prefix = q.front();
q.pop();
for (char ch : keypad[d - '0']) {
q.push(prefix + ch);
}
}
}
while (!q.empty()) {
result.push_back(q.front());
q.pop();
}
return result;
}
};
JavaScriptTested in our runner
/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function(digits) {
if (digits.length === 0) {
return [];
}
const keypad = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];
let queue = [""];
for (const d of digits) {
// the old layer is consumed front to back, the new layer is built behind it
const next = [];
for (const prefix of queue) {
for (const ch of keypad[Number(d)]) {
next.push(prefix + ch);
}
}
queue = next;
}
return queue;
};
GoTested in our runner
func letterCombinations(digits string) []string {
n := len(digits)
if n == 0 {
return []string{}
}
keypad := [10]string{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
queue := []string{""}
for i := 0; i < n; i++ {
letters := keypad[digits[i]-'0']
// the old layer is consumed front to back, the new layer is built behind it
next := make([]string, 0, len(queue)*len(letters))
for _, prefix := range queue {
for j := 0; j < len(letters); j++ {
next = append(next, prefix+string(letters[j]))
}
}
queue = next
}
return queue
}
C#Tested in our runner
public class Solution {
private static readonly string[] Keypad = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
public string[] letterCombinations(string digits) {
if (digits.Length == 0) {
return new string[0];
}
var queue = new Queue<string>();
queue.Enqueue("");
foreach (char d in digits) {
string letters = Keypad[d - '0'];
// expand exactly the prefixes that belong to the current layer
int size = queue.Count;
for (int k = 0; k < size; k++) {
string prefix = queue.Dequeue();
foreach (char ch in letters) {
queue.Enqueue(prefix + ch);
}
}
}
return queue.ToArray();
}
}

Solution pattern
Subsets (Include/Exclude)
Part of Backtracking Patterns
Approach 3: Backtracking with one shared pathOptimalSubsets (Include/Exclude)
What's slow: the queue holds every prefix of the current layer plus the next layer, and it creates a new string for every prefix. Most of that storage is intermediate and gets thrown away.
The insight that fixes it: walk the decision tree depth first and keep a single mutable path. At depth i, try each letter of digits[i]: append it, recurse to depth i + 1, then remove it. When the depth reaches n, the path is a full combination, so copy it into the result. Only one root-to-leaf path exists in memory at a time, so extra space is O(n) beyond the answer.
Steps
- If
digitsis empty, return an empty list. - Store the keypad as a table indexed by digit value.
- Define
backtrack(i)with a sharedpathlist and a sharedresultlist. - If
i == n, joinpathinto a string, add it toresult, and return. - Otherwise loop over each letter mapped to
digits[i]. - Append the letter to
path, callbacktrack(i + 1), then remove the last letter. - Call
backtrack(0)and returnresult.
Dry run
Take digits = "279". Each row is one action in the search.
| Step | Depth i | Path after action | Action | Results so far |
|---|---|---|---|---|
| 1 | 0 | a | pick a from abc | 0 |
| 2 | 1 | ap | pick p from pqrs | 0 |
| 3 | 2 | apw | pick w from wxyz | 0 |
| 4 | 3 | apw | depth equals n, record apw | 1 |
| 5 | 2 | apx | pop w, pick x, record at depth 3 | 2 |
| 6 | 2 | apy | pop x, pick y, record | 3 |
| 7 | 2 | apz | pop y, pick z, record | 4 |
| 8 | 1 | aq | letters of wxyz used up, pop z and p, pick q | 4 |
| 9 | 2 | aqw | pick w, record at depth 3 | 5 |
| 10 | 1 | as | finish aqx to aqz, then r and s branches, 12 leaves under a | 12 |
| 11 | 0 | b | pop s and a, pick b, repeat: 12 more leaves | 24 |
| 12 | 0 | c | pop b, pick c, repeat: 12 more leaves, last is csz | 48 |
The search ends after csz is recorded, because depth 0 has no letters of abc left. The 48 results come out in alphabetical order, matching the expected output.
Complexity
| Time | O(n * 4^n) |
|---|---|
| Space | O(n) extra, plus the output |
Here n is the length of digits. The tree has at most 4^n leaves, and the internal nodes number at most about 4^n / 3 * 4 more, so the total node count is O(4^n). Each leaf copies a path of n characters, which costs O(n), so time is O(n * 4^n). Auxiliary space is the recursion stack of depth n plus the path of n characters, so O(n), and the output list is not counted.
PythonTested in our runner
from typing import List, Optional
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []
keypad = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
n = len(digits)
result = []
path = []
def backtrack(i: int) -> None:
# a full path has one letter per digit
if i == n:
result.append("".join(path))
return
for ch in keypad[int(digits[i])]:
path.append(ch) # choose
backtrack(i + 1) # explore
path.pop() # undo
backtrack(0)
return result
JavaTested in our runner
import java.util.*;
class Solution {
private static final String[] KEYPAD = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public String[] letterCombinations(String digits) {
if (digits.length() == 0) {
return new String[0];
}
List<String> result = new ArrayList<>();
backtrack(digits, 0, new StringBuilder(), result);
return result.toArray(new String[0]);
}
private void backtrack(String digits, int i, StringBuilder path, List<String> result) {
// a full path has one letter per digit
if (i == digits.length()) {
result.add(path.toString());
return;
}
String letters = KEYPAD[digits.charAt(i) - '0'];
for (int j = 0; j < letters.length(); j++) {
path.append(letters.charAt(j)); // choose
backtrack(digits, i + 1, path, result); // explore
path.deleteCharAt(path.length() - 1); // undo
}
}
}
C++Tested in our runner
using namespace std;
class Solution {
public:
vector<string> letterCombinations(string digits) {
vector<string> result;
if (digits.empty()) {
return result;
}
string path;
backtrack(digits, 0, path, result);
return result;
}
private:
const vector<string> keypad = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
void backtrack(const string& digits, int i, string& path, vector<string>& result) {
// a full path has one letter per digit
if (i == (int)digits.size()) {
result.push_back(path);
return;
}
for (char ch : keypad[digits[i] - '0']) {
path.push_back(ch); // choose
backtrack(digits, i + 1, path, result); // explore
path.pop_back(); // undo
}
}
};
JavaScriptTested in our runner
/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function(digits) {
const n = digits.length;
if (n === 0) {
return [];
}
const keypad = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];
const result = [];
const path = [];
const backtrack = (i) => {
// a full path has one letter per digit
if (i === n) {
result.push(path.join(""));
return;
}
for (const ch of keypad[Number(digits[i])]) {
path.push(ch); // choose
backtrack(i + 1); // explore
path.pop(); // undo
}
};
backtrack(0);
return result;
};
GoTested in our runner
func letterCombinations(digits string) []string {
n := len(digits)
result := []string{}
if n == 0 {
return result
}
keypad := [10]string{"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
path := make([]byte, 0, n)
var backtrack func(i int)
backtrack = func(i int) {
// a full path has one letter per digit
if i == n {
result = append(result, string(path))
return
}
letters := keypad[digits[i]-'0']
for j := 0; j < len(letters); j++ {
path = append(path, letters[j]) // choose
backtrack(i + 1) // explore
path = path[:len(path)-1] // undo
}
}
backtrack(0)
return result
}
C#Tested in our runner
using System.Text;
public class Solution {
private static readonly string[] Keypad = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
public string[] letterCombinations(string digits) {
if (digits.Length == 0) {
return new string[0];
}
var result = new List<string>();
Backtrack(digits, 0, new StringBuilder(), result);
return result.ToArray();
}
private void Backtrack(string digits, int i, StringBuilder path, List<string> result) {
// a full path has one letter per digit
if (i == digits.Length) {
result.Add(path.ToString());
return;
}
foreach (char ch in Keypad[digits[i] - '0']) {
path.Append(ch); // choose
Backtrack(digits, i + 1, path, result); // explore
path.Length--; // undo
}
}
}
Common mistakes
- Skipping the guard for empty input. With
digits = ""the base casei == nis true on the first call, so you record""and return[""]. Addif not digits: return []before the recursion. - Forgetting the undo step, such as leaving out
path.pop()ordeleteCharAt. The path keeps growing, and later results contain letters from earlier branches. Remove the last letter right after the recursive call returns. - Appending the shared list itself, as in
result.append(path)in Python. Every entry then points to the same list, which ends up empty. Join or copy the path at the leaf with"".join(path). - Indexing the keypad with the character instead of its value, like
keypad[digits[i]]in C++ or Java. The character'2'is code 50, which is out of range. Convert withdigits[i] - '0'before the lookup. - Building a keypad with the wrong offset, such as an 8-slot array that starts at digit 2 but is indexed by the raw digit. Use a 10-slot table with empty strings at slots 0 and 1, or subtract 2 consistently.
- Using
current + letterstring concatenation at every call and forgetting that it copies. It is correct for n up to 4, but it hides the O(n) cost per step. Prefer one mutable buffer and copy only at the leaf.
Edge cases
digits = ""must return[], an empty list with no strings in it.- A single digit such as
"2"returns["a","b","c"], and"7"returns four strings,["p","q","r","s"]. - A repeated digit like
"22"returns 9 strings, includingaa,abandcc. Repeats are independent positions, not a deduplication case. - The largest branching,
"7979", returns 4 * 4 * 4 * 4 = 256 strings, each of length 4. - Mixed sizes such as
"23"give 3 * 3 = 9 strings, while"79"gives 16. The count is always the product of the letter counts. - The smallest valid result for a nonempty input is 3 strings, because every digit from 2 to 9 maps to at least 3 letters.
Follow-ups interviewers ask
- The input can now be longer. Does the solution change, and what limits it?
- The algorithm stays the same. Time is O(n * 4^n) and the output itself has up to 4^n strings, so the limit is the size of the answer, not the method. If the caller only needs to consume results one by one, turn the recursion into a generator so you never hold all strings at once.
- How would you do this iteratively without a queue of prefixes?
- Use an odometer. Keep an array of indexes, one per digit, each pointing to a letter of that digit. Build the string from the indexes, then advance the last index. When an index reaches its digit's letter count, reset it to 0 and carry to the position on the left. Stop when the carry runs off the front. This uses O(n) extra space and produces alphabetical order.
- What if digits can be 0 or 1, which map to no letters?
- Then any input containing a digit with no letters has zero valid combinations, so the answer is an empty list. Check for such a digit first and return early. A different reading treats 0 and 1 as themselves, in which case you map them to the one-character strings
0and1and the same code works.
Letter Combinations of a Phone Number FAQ
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. Digits 7 and 9 have 4 letters, so there are at most 4^n results, and each result is a string of length n that costs O(n) to build. With n at most 4, that is at most 256 strings of length 4.
Why use backtracking for Letter Combinations of a Phone Number?
The answer is built by making one choice per digit, and the number of digits changes from input to input. Backtracking uses recursion depth in place of a variable number of nested loops. It also keeps one shared path, so it needs only O(n) extra space beyond the output.
Can Letter Combinations of a Phone Number be solved in O(1) extra space?
Not strictly. The recursive version needs O(n) space for the stack and path. An odometer-style loop needs an index per digit, which is also O(n). Since n is at most 4 here, both are effectively constant in practice, but they are not O(1) in the formal sense.
Why does the empty string input return an empty list and not a list with an empty string?
The problem defines no digits as no combinations. A plain recursive solution would treat zero digits as one empty combination, so you must return [] early to match the expected answer.
Is the iterative queue solution better than recursion for LeetCode 17?
Both run in O(n * 4^n) time. The queue version avoids recursion but keeps a full layer of prefixes in memory, so it uses O(n * 4^n) space. Backtracking keeps one path and uses O(n) auxiliary space, which is why it is the usual interview answer.
Does the order of the output matter for LeetCode 17?
No, the problem accepts any order. All three approaches here produce alphabetical order because they process letters in keypad order, which is convenient when you compare your output with an example by eye.
Asked at
See which companies ask this — Pro
Related problems
- Subsets · same technique: Subsets (Include/Exclude)
- Subsets II · same technique: Subsets (Include/Exclude)
- Combinations · same technique: Subsets (Include/Exclude)
- Sum of All Subset XOR Totals · same technique: Subsets (Include/Exclude)
- N-Queens · next harder, same pattern
- Word Search · same pattern: Backtracking Patterns
- Permutations · same pattern: Backtracking Patterns
- Combination Sum · same pattern: Backtracking Patterns
- Generate Parentheses · same pattern: Backtracking Patterns
- Palindrome Partitioning · same pattern: Backtracking Patterns