Letter Combinations of a Phone Number
Depth-first search over telephone keypad mappings
Each digit on a phone keypad maps to a discrete set of letters (2="abc", 3="def"). Generating all combinations is a depth-first tree traversal where depth corresponds to digit index. At depth i, iterate through every letter mapped to digits[i], append it to the current path, recurse to depth i+1, and pop the letter (backtrack) upon return. When depth reaches the length of digits, the path forms a complete combination.
Details
Animated on: digits = "23" — return all possible letter combinations that the numbers could represent (2 maps to "abc", 3 maps to "def").
Problem:Letter Combinations of a Phone NumberMedium
Pattern:Backtracking with Constraints
Depth-first search over telephone keypad mappings
step 1 / 12
idx=0 (digit '2' → 'abc'): choose letter 'a'. path = ['a']. Recurse to idx=1.
- idx:0=0· arr[0] = a
1FUNCTION letterCombinations(digits):2 IF digits is empty: RETURN empty list3 phone = a table mapping each digit to its letters ('2'->'abc', '3'->'def')4 ans = empty list of results, path = empty current combination5 FUNCTION backtrack(idx):6 IF idx equals the length of digits: join path into a string and add it to ans; RETURN7 FOR each letter mapped to digits[idx]:8 add letter to path; backtrack(idx + 1); remove the last letter from path9 END FOR10 backtrack(0); RETURN ans
← / → step · space play · Home restart
Every step in words
Show all 12 steps
- idx=0 (digit '2' → 'abc'): choose letter 'a'. path = ['a']. Recurse to idx=1.
- idx=1 (digit '3' → 'def'): choose 'd'. path = ['a', 'd']. Leaf reached! Record 'ad'. ans=['ad'].
- Backtrack: pop 'd', push 'e'. path = ['a', 'e']. Leaf reached! Record 'ae'. ans=['ad', 'ae'].
- Backtrack: pop 'e', push 'f'. path = ['a', 'f']. Leaf reached! Record 'af'. ans=['ad', 'ae', 'af'].
- Backtrack to idx=0: digit 2 advances to next choice 'b'. path = ['b']. Recurse to idx=1.
- At idx=1: choose 'd' → 'bd'. Backtrack and try 'e' → 'be', then 'f' → 'bf'. ans now has 6 combinations.
- Branch for 'b' completes with 'bf'. ans=['ad', 'ae', 'af', 'bd', 'be', 'bf'].
- Backtrack to idx=0: digit 2 advances to final choice 'c'. path = ['c']. Recurse to idx=1.
- At idx=1: choose 'd' → path=['c', 'd']. Leaf! Record 'cd'.
- Backtrack and choose 'e' → path=['c', 'e']. Leaf! Record 'ce'.
- Backtrack and choose 'f' → path=['c', 'f']. Leaf! Record 'cf'.
- All combinations generated. Return ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf'] (9 combinations total).
Now solve it yourself
Watching is the first half. The second is writing it without the animation.