← DSA
MEDIUM

Letter Combinations of a Phone Number

PracticeNeetCode ↗LeetCode ↗

Given a string of digits from 2–9, return every possible letter combination the number could represent on a standard phone keypad, in any order.

Example

Input digits = "23"
Output ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Key Pointers

Step-by-Step Analysis

  1. If digits is empty, return [].
  2. Build a digit → letters lookup table ("2": "abc", "3": "def", and so on).
  3. Define backtrack(index): if index == len(digits), record "".join(path).
  4. Otherwise loop over every letter mapped to digits[index]: append the letter, recurse with backtrack(index + 1), then pop.
  5. Call backtrack(0) and return the result.

Complexity

Time: O(4ⁿ · n) — Space: O(n) recursion depth

Code

def letterCombinations(digits: str) -> list[str]:
    if not digits:
        return []

    mapping = {
        "2": "abc", "3": "def", "4": "ghi", "5": "jkl",
        "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz",
    }
    result = []
    path = []

    def backtrack(index: int) -> None:
        if index == len(digits):
            result.append("".join(path))
            return
        for letter in mapping[digits[index]]:
            path.append(letter)
            backtrack(index + 1)
            path.pop()

    backtrack(0)
    return result

Code Explanation

How the solution above works, piece by piece.

  1. An empty input returns an empty list (not [""]).
  2. mapping gives each digit's letters, as on a phone keypad.
  3. backtrack(index) chooses a letter for digits[index]. When every digit has a letter, join path into a string.
  4. Loop over that digit's letters: append, recurse to the next digit, pop.
  5. Up to 4ⁿ combinations (7 and 9 have four letters), each built in O(n): O(n · 4ⁿ).

Visual Walkthrough

The recursion tree for digits = "23":

Letter combinations tree for 23""aadaeafbbdbebfccdcecfdigit 2: a b cdigit 3: d e f
Level 1 picks a letter for the first digit (2 → a, b, c); level 2 picks a letter for the second digit (3 → d, e, f). Each of the 3 × 3 = 9 leaves is one combination.
combination

Video Explanation

NeetCode — Backtracking, LeetCode 17