Letter Combinations of a Phone Number, explained
Letter Combinations of a Phone Number asks for every word you could spell by pressing a given sequence of keys on an old phone keypad. Solve it with backtracking: for each digit in turn, try each of its letters, append it, recurse to the next digit, then remove it, saving the word when every digit has a letter. With up to four letters per key, there are at most 4^n results of length n, so the time is O(n · 4^n).
By Evin JohnPublished 9 min read
What the problem asks
A classic phone keypad prints letters under the digits 2 through 9: 2 has abc, 3 has def, 4 has ghi, 5 has jkl, 6 has mno, 7 has pqrs, 8 has tuv and 9 has wxyz. You receive a string of those digits. Produce every string that picks exactly one letter for each digit, in the same order as the digits. The order of the output list usually does not matter.
"8" -> t u v (3 results)
"52" -> ja jb jc ka kb kc la lb lc (3 x 3 = 9 results)
"79" -> pw px py pz qw ... sz (4 x 4 = 16 results)
"" -> (empty list)Clarify three things before writing code. First, what should an empty string return? Most versions expect an empty list, not a list holding one empty string, and the two are easy to confuse. Second, can 0 or 1 appear? They carry no letters on the keypad, so either the input excludes them or you must decide whether they are skipped or make the whole answer empty. Third, how long can the input be? Each extra digit multiplies the output by three or four, so lengths are kept small in practice.
What the interviewer is looking for
This is often the first backtracking question in a loop, used as a warm-up. Nobody is testing whether you can find a clever trick; there is none. They want a tidy recursion with a clear base case, correct handling of the empty input, and a confident statement that the output size sets the running time. A candidate who writes it cleanly in a few minutes earns room for a harder follow-up.
A first approach: grow the words level by level
Start with a list holding one empty word. For each digit, build a new list by attaching each of that digit's letters to every word in the current list. After the last digit, the list holds every answer. This is breadth-first in spirit and needs no recursion. Its weakness is memory: it keeps every partial word of the current length at once, which is no worse than the final output but does create many short-lived strings along the way.
KEYS = {
"2": "abc", "3": "def", "4": "ghi", "5": "jkl",
"6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz",
}
def combos_by_level(digits):
if not digits:
return []
words = [""]
for d in digits:
words = [w + ch for w in words for ch in KEYS[d]]
return wordsThe expected answer: backtracking
Backtracking builds one word at a time in a shared buffer. The function receives the index of the digit it must fill. If the index equals the number of digits, the buffer is a finished word: join it and save it. Otherwise, loop over the letters for that digit, put the letter in the buffer, call the function for the next index, and take the letter out again. The tree it walks has one level per digit and a branching factor of three or four.
def letter_combinations(digits):
if not digits:
return []
keys = {
"2": "abc", "3": "def", "4": "ghi", "5": "jkl",
"6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz",
}
out, buf = [], []
def fill(i):
if i == len(digits):
out.append("".join(buf))
return
for ch in keys[digits[i]]:
buf.append(ch)
fill(i + 1)
buf.pop()
fill(0)
return outconst KEYPAD = {
2: "abc", 3: "def", 4: "ghi", 5: "jkl",
6: "mno", 7: "pqrs", 8: "tuv", 9: "wxyz",
};
function letterCombinations(digits) {
if (digits.length === 0) return [];
const out = [];
const buf = [];
const fill = (i) => {
if (i === digits.length) {
out.push(buf.join(""));
return;
}
for (const ch of KEYPAD[digits[i]]) {
buf.push(ch);
fill(i + 1);
buf.pop();
}
};
fill(0);
return out;
}Both produce the words in the order the keypad lists the letters, which happens to be alphabetical for each position, so the output comes out sorted. That is a useful side effect to mention if the interviewer cares about order. In Python, itertools.product over the letter groups gives the same result in one line; it is fine to say so, but write the recursion anyway, since the point of the question is to show you can.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Level-by-level product | O(n · 4^n) | O(n · 4^n) for the lists of partial words |
| Backtracking with a buffer | O(n · 4^n) | O(n) for the recursion and buffer, plus the output |
| Count only (follow-up) | O(n) | O(1) |
| k-th word only (follow-up) | O(n) | O(n) |
The 4^n is an upper bound. The exact number of results is the product of the key sizes, for example 3 × 4 = 12 for "27". Each result takes O(n) to build, hence the extra factor of n. Since that is the size of the output, no method can do better when you must return every word.
Follow-ups you may get
- How many results, without listing them? Multiply the key sizes. For "79" that is 16.
- Return only the k-th word in sorted order. Treat the word as a number in a mixed base, where each position's base is that key's letter count, and peel off digits from the right.
- Keep only real words from a dictionary. Map each dictionary word to its key sequence once, then look up the input. Or walk a trie of the dictionary during the backtracking and prune any prefix that is not in it.
- Digits 0 and 1 are allowed. Decide with the interviewer: skip them, map them to themselves, or treat them as making the result empty. Then handle that in one place.
- Stream the results instead of storing them. Turn the function into a generator so memory stays O(n).
def kth_combination(digits, k):
keys = {
"2": "abc", "3": "def", "4": "ghi", "5": "jkl",
"6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz",
}
groups = [keys[d] for d in digits]
total = 1
for g in groups:
total *= len(g)
if not digits or not 0 <= k < total:
raise IndexError("k out of range")
letters = []
for g in reversed(groups):
k, r = divmod(k, len(g))
letters.append(g[r])
return "".join(reversed(letters))For "52" the sorted list is ja, jb, jc, ka, kb, kc, la, lb, lc, so k = 4 gives "kb": 4 divided by 3 leaves remainder 1 (the b in abc) and quotient 1 (the k in jkl). Walking through one small case like this is the fastest way to convince an interviewer the mixed-base idea is right.
Edge cases
- Empty input: return an empty list, unless told otherwise.
- A single digit: just its letters.
- Digits with four letters (7 and 9) next to digits with three, so the code does not assume a fixed width.
- Repeated digits such as "22": nine results, including "aa" and "cc".
- Characters outside 2 to 9, if the input is not guaranteed clean.
Common slips
- Returning [""] for empty input because the base case fires at index 0.
- Building the string by concatenation and also appending to a buffer, so letters appear twice.
- Forgetting the pop after the recursive call.
- Hard-coding three letters per key and losing the s in pqrs or the z in wxyz.
- Stating the time as O(4^n) and dropping the cost of building each word, or calling it O(n) because the input is short.
Talking through it
Fictional example
- Candidate
- Each digit gives three or four choices and I need one choice per digit, so this is a Cartesian product. I will generate it with backtracking: one recursion level per digit.
- Candidate
- The base case is when I have placed a letter for every digit; I join the buffer and save it. An empty input returns an empty list, which I handle before the recursion starts.
- Candidate
- There are at most four to the n words and each costs n to build, so it is n times four to the n. That is the output size, so it cannot be improved for the full list.
- Interviewer
- And if I only wanted the hundredth word?
- Candidate
- Then I would treat the word as a number in a mixed base and convert 99 into it, one key at a time from the right. Linear in the number of digits.
Related problems
Here every branch is valid. In Palindrome Partitioning most branches die early because a piece is not a palindrome, and in N-Queens pruning is the whole game. Comparing the three shows how the same template changes when the constraint gets tighter. For breadth-first search on a grid instead, see Rotting Oranges.
Where Natively fits
A warm-up like this is a good place to rehearse speaking while you type. In a practice session, Natively can read the problem from a screenshot, outline a backtracking solution in the language you choose, and transcribe what you said, so afterward you can check whether you stated the empty-input case and the output-size bound out loud. It runs on Mac and Windows; more on using it as an interview assistant.
Questions people ask
How do you solve Letter Combinations of a Phone Number?
Map each digit to its keypad letters, then backtrack: for the current digit, try each letter, add it to a buffer, recurse to the next digit and remove it afterward. When every digit has a letter, save the joined buffer.
What is the time complexity?
O(n · 4^n) for n digits. There are at most four letters per key, so at most 4^n words, and building each one costs O(n). That equals the output size, so it cannot be beaten when every word is returned.
What should an empty input return?
Usually an empty list. A recursive solution that reaches its base case immediately returns a list holding one empty string instead, so check for empty input before starting the recursion and confirm the expected value with the interviewer.
Can you solve it without recursion?
Yes. Start with one empty word and, for each digit, extend every word so far with each of that digit's letters. In Python, itertools.product over the letter groups does the same in one line.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
