Letter Combinations of a Phone Number
List every letter string a digit string can spell on a phone keypad, one letter per digit.
The problem
You get a string digits made of the digits 2 to 9. On a phone keypad each of these digits stands for a few letters: 2 is abc, 3 is def, 4 is ghi, 5 is jkl, 6 is mno, 7 is pqrs, 8 is tuv and 9 is wxyz. Return every string you can form by picking one letter for each digit, in any order, and return an empty list when digits is empty.
Input digits = "47"
Output ["gp", "gq", "gr", "gs", "hp", "hq", "hr", "hs", "ip", "iq", "ir", "is"]
4 offers g, h, i and 7 offers p, q, r, s, so there are 3 * 4 = 12 strings.
Input digits = "8"
Output ["t", "u", "v"]
A single digit gives one string per letter on its key.
Key constraint: digits has at most 4 digits and each key has 3 or 4 letters, so there are at most 4^4 = 256 strings.
How to spot the pattern
- You must build every string where each position has a small fixed set of options.
- The number of positions depends on the input, so a fixed number of nested loops can't do it.
The idea
With exactly two digits, two nested loops would do. The number of digits varies, so let recursion play the role of the loops: position i tries each letter of digits[i] and hands the rest of the work to position i + 1. Once every digit has a letter, the letters chosen so far form one answer.
Brute force: Write one nested loop per digit, which only works for one fixed input length and has to be rewritten for every other length.
Step by step
- 1If
digitsis empty, return an empty list. - 2Map each digit to the letters on its key.
- 3Write
backtrack(i); wheniequals the length ofdigits, save the chosen letters as a string. - 4Otherwise, for each letter of
digits[i], append it, callbacktrack(i + 1)and remove it again.
See the pattern move
The backtracking pattern on a small example. Step through it, or press play.
Code
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if not digits:
return []
keys = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl",
"6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}
result = []
current = []
def backtrack(i: int) -> None:
if i == len(digits):
result.append("".join(current))
return
for letter in keys[digits[i]]:
current.append(letter) # choose a letter for digit i
backtrack(i + 1)
current.pop() # undo it
backtrack(0)
return resultComplexity
Time
O(4^n * n)
Space
O(n)
Up to 4^n strings of length n are built; the recursion and the current letters hold n characters, not counting the output.
Watch out for
- Returning
[""]for empty input, when the expected answer is an empty list. - Forgetting to remove the last letter after the recursive call when you build into a shared list or StringBuilder.
- Giving every key three letters: 7 (pqrs) and 9 (wxyz) have four.
Follow-up questions
Can you do it without recursion?
Start with [""] and, for each digit, replace the list with every string extended by each letter of that digit. It builds exactly the same strings, level by level.
What if you only want combinations that are real words?
Store the dictionary in a trie and stop extending a prefix as soon as the trie has no word starting with it, which cuts most branches early.
In Hinglish
Har digit ke letters mein se ek chuno aur agli digit ka kaam recursion ko de do. Saari digits ka letter chun liya toh woh string answer mein daal do.