Spell every word a phone number could make. Fill one position at a time from its key, recurse for the rest, then pop and try the next letter.
▼The problem
LeetCode 17, Letter Combinations of a Phone Number (Medium). Given a string of digits 2-9, return every letter string the number could represent on a phone keypad (2 = abc, 3 = def, ..., 7 = pqrs, 9 = wxyz), one letter from each key. An empty input returns [].
Example: "23" → ["ad","ae","af","bd","be","bf","cd","ce","cf"] (9 = 3 × 3, in the order the backtracking saves them).
The solution
KEYS = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
'6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
def letter_combinations(digits):
out = []
def go(i, path):
if i == len(digits):
out.append(''.join(path)) # save
return
for ch in KEYS[digits[i]]:
path.append(ch) # append
go(i + 1, path) # recurse
path.pop() # pop
if digits:
go(0, [])
return outTranscript
Letter Combinations of a Phone Number. On a phone keypad, each digit from two to nine carries three letters, and seven and nine carry four. Given some digits, return every string they could spell, one letter from each key.
Take two, three. Two carries A, B, C. Three carries D, E, F. Pair each letter of two with each letter of three: A D, A E, A F, and so on, up to C F. Three times three: nine strings.
For two digits, two nested loops would do it. But three digits need three loops, ten digits need ten, and you don't know how many digits you'll get.
So let recursion nest the loops for you. That's backtracking. Build the string one position at a time. Try each letter on that digit's key: append it, fill the rest the same way, then pop it off and try the next. When every position is filled, that's one answer.
Picture it as a tree. The first digit splits the empty string three ways: A, B, C. Each branch splits three more ways: D, E, F. Nine leaves, nine answers.
Let's walk two, three. Append A, then D: full, so save A D. Pop D, try E: A E. Then A F. Three is out of letters, so back up to B: B D, B E, B F. Then C: C D, C E, C F. Nine strings.
In code, a helper takes the position and the path so far. If the path is full, join it and save it. Otherwise, for each letter on this digit's key: append, recurse one position deeper, pop. Start at position zero, if there are any digits at all.
Each key has at most four letters, so n digits give at most four to the n strings, each n long. That's order n times four to the n time. Two, three, four gives twenty seven. The recursion is only n deep, so the extra space is order n.
Pick a letter, go deeper, back up, try the next. That's Letter Combinations.