Letter Combinations of a Phone Number

Medium

Topics
StringBacktrackingHash Table

Given a string of digits from 2-9, return all letter combinations the number could spell (phone keypad mapping). Return an empty result for an empty input. Order does not matter.

Example 1

digits23
keys2: abc3: def
answersadaeafbdbebfcdcecf
Each digit contributes one letter, so the count is the product of the key sizes — 9 here. An empty input has no combinations, not one, which is the edge case most solutions get wrong.
The digits, the letters each one offers, and the resulting strings.
Input:  digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Example 2

empty array
Input:  digits = ""
Output: []

Constraints

  • 0 <= digits.length <= 4
  • digits[i] is in the range 2-9.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Each digit maps to a set of letters; the answer is the Cartesian product across digits. Grow the set of prefixes one digit at a time.

Approach

  1. Map digits to their letters.
  2. Start with an empty prefix; for each digit, extend every current prefix by each mapped letter.
  3. Return the accumulated combinations (empty input gives an empty list).

Dry Run

digits = "23"
This one is iterative rather than recursive: each digit multiplies the set of
prefixes built so far.
  res starts as [""]  --  exactly one empty prefix to extend
  digit 2 (abc)   res = [a, b, c]
  digit 3 (def)   res = [ad, ae, af, bd, be, bf, cd, ce, cf]
answer ad ae af bd be bf cd ce cf
The seed has to be [""] and not []. A single empty prefix is what the first digit
extends; seed it with an empty LIST and the comprehension iterates over nothing,
so the result stays empty no matter how many digits follow.
Which makes the empty-input guard necessary rather than defensive. With no digits
the loop never runs and res is still [""], so the function would return a list
containing one empty string -- measured as [''] -- where the answer is []. One
case where the identity element of the construction is not the answer.
Size grows as the product of the digit alphabets, 3 x 3 = 9 here and up to 4^n for
strings of 7s and 9s, which is why the output itself dominates the complexity.

Complexity

  • Time — O(4^n): up to 4 letters per digit across n digits.
  • Space — O(4^n): the output list.

Common Pitfalls

  • Return [] (not [""]) for an empty input.

Full Solution — all languages

class Solution:
    def letterCombinations(self, digits):
        if not digits: return []
        m={'2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno','7':'pqrs','8':'tuv','9':'wxyz'}
        res=['']
        for d in digits:
            res=[p+c for p in res for c in m[d]]
        return res
SensAI
Beta
Tap the mic to stop voice mode