CodeArchon

mediumBacktrackingFacebookAmazonUber

Dialpad Dictionary Dialer

A T9 keypad emits every possible letter combination for a dialed digit sequence (e.g. '23' -> ad, ae, …, cf).

Given a string of digits 2-9, return all possible letter combinations the number could represent (using the standard phone keypad mapping).

Choose approach

2
0
3
1
i
SetCombinations (0)
empty
1/21
Narrationstep 1 of 21

Pick 'a' from digit 2.

1def letterCombinations(digits):
2 if not digits: return []
3 m = {'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
4 out, cur = [], []
5 def dfs(i):
6 if i == len(digits):
7 out.append(''.join(cur)); return
8 for c in m[digits[i]]:
9 cur.append(c); dfs(i+1); cur.pop()
10 dfs(0); return out
Variables
cur=a
out=0

How to think about it

  1. Static digit→letters map.
  2. DFS tree width ≤ 4, depth = number of digits.
  3. Empty input -> empty output (not a single empty string).

Edge cases to catch in interview

  • Digits with no letters (0, 1) -> interview constraint typically excludes.
  • Empty string input -> return empty list, not [''].

Examples

Example 1["ad","ae","af","bd","be","bf","cd","ce","cf"]
{"digits":"23","values":["2","3"]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed