Tensorum
LeetCode 17 · Combinations

Letter Combinations of a Phone Number

LeetCode 17 · Medium · solution, intuition & step-by-step walkthrough

One recursion level per digit.

MediumHash TableStringBacktracking
0 msruntime · beats 100%
19.3 MBmemory · beats 45%
1approach
3accepted runs · last 1 Apr 2026

This is how I solved Letter Combinations of a Phone Number (LeetCode 17), a medium problem from the Combinations pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

Each digit offers 3–4 letters. Walk the digits left to right, trying each letter for the current digit and recursing on the next; a full-length combination is one answer.

Approach

  1. 1

    Empty input → [].

  2. 2

    dfs(index, comb): full length → join and record.

  3. 3

    For each letter of digits[index], append, recurse, pop.

How I solved it

BacktrackingPythonO(4ⁿ·n) time
class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits:
            return []
        letters = {
            "2": "abc",
            "3": "def",
            "4": "ghi",
            "5": "jkl",
            "6": "mno",
            "7": "pqrs", #4
            "8": "tuv",
            "9": "wxyz", #4
        }
        res = []
        def dfs(index,comb):
            if len(comb)==len(digits):
                res.append("".join(comb))
                return
            cur_digit = digits[index]
            cur_letters = letters[cur_digit]
            for letter in cur_letters:
                comb.append(letter)
                dfs(index+1,comb)
                comb.pop()
        dfs(0,[])
        return res
Loading the step-through…

Letter Combinations of a Phone Number — FAQ

What is the intuition behind Letter Combinations of a Phone Number?

Each digit offers 3–4 letters. Walk the digits left to right, trying each letter for the current digit and recursing on the next; a full-length combination is one answer.

How do you solve Letter Combinations of a Phone Number (LeetCode 17)?

1. Empty input → []. 2. dfs(index, comb): full length → join and record. 3. For each letter of digits[index], append, recurse, pop.

What is the time and space complexity of Letter Combinations of a Phone Number?

Time: O(4ⁿ · n). Space: O(n). (Accepted approach: Backtracking.)

What are common mistakes in Letter Combinations of a Phone Number?

Empty input must return [] rather than [''].