Skip to content
Problem 17 · LeetCode 17(opens in a new tab)

Letter Combinations of a Phone Number

MediumBacktracking

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.

Try it on LeetCode(opens in a new tab)
  1. Grow the list one digit at a timeO(4ⁿ · n)
  2. BacktrackingO(4ⁿ · n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 4 digitsVerdict
Grow the list one digit at a timeO(4ⁿ · n)
Short; keeps whole lists in memory
BacktrackingO(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 path itself instead of a copy or a joined string, so every saved result changes later.

How to talk through it

  1. 1Clarify. Which digits can appear, and can the string be empty? Does the order of results matter?
  2. 2Count the output. Up to 4ⁿ strings of length n, so the time is at least that.
  3. 3Choose and recurse. One letter per digit, then recurse on the next digit, then undo.
  4. 4Mention the iterative version. Growing a list digit by digit gives the same strings without recursion.
  5. 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?