On a phone keypad, each digit from 2 to 9 has 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.
You get a string digits made of those digits. Return every string you could spell by picking one letter for each digit, in the same order as the digits. Any order of the results is fine.
Example 1
Input: digits = "56" Output: ["jm", "jn", "jo", "km", "kn", "ko", "lm", "ln", "lo"] Why: 3 letters for 5 times 3 letters for 6 gives 9 strings
1 more example and the constraints
Example 2
Input: digits = "8" Output: ["t", "u", "v"] Why: one digit, so each of its letters is a result on its own
Constraints
- 1 ≤ length of digits ≤ 4
- Each character of digits is between '2' and '9'
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Grow the list one digit at a timeO(4ⁿ · n)
- BacktrackingO(4ⁿ · n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 4 digits | Verdict |
|---|---|---|---|
| Grow the list one digit at a time | O(4ⁿ · n) | Short; keeps whole lists in memory | |
| Backtracking | O(4ⁿ · n) | Best; the pattern interviewers expect |
n = number of digits. 4ⁿ is the worst case, when every digit is 7 or 9.
Edge cases to test
- One digit. "8" returns its letters one by one: ["t", "u", "v"].
- Four-letter keys. 7 and 9 have four letters, so "79" gives 16 strings, not 9.
- Repeated digits. "22" pairs abc with abc again: 9 strings, including "aa".
- Four digits. "7999" gives 4 × 4 × 4 × 4 = 256 strings, the most possible.
Common mistakes
- Forgetting to pop the letter after the recursive call, so later strings keep old letters.
- Giving every key three letters, which drops the s of 7 and the z of 9.
- Saving
pathitself instead of a copy or a joined string, so every saved result changes later.
How to talk through it
- 1Clarify. Which digits can appear, and can the string be empty? Does the order of results matter?
- 2Count the output. Up to 4ⁿ strings of length n, so the time is at least that.
- 3Choose and recurse. One letter per digit, then recurse on the next digit, then undo.
- 4Mention the iterative version. Growing a list digit by digit gives the same strings without recursion.
- 5Test out loud. Run "56" and a digit with four letters like "7".
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?