SDE & MLE Prep

17. Letter Combinations of a Phone Number

Problem

On a phone keypad, 2 maps to abc, 3 to def, …, 7 to pqrs, 8 to tuv, 9 to wxyz. Given a string of digits 2–9, return every letter string it could spell, in any order (an empty input gives an empty list).

Example: "23" → ["ad","ae","af","bd","be","bf","cd","ce","cf"]

Constraints: at most 4 digits.

Depth = digit index; branch over that digit's letters.

Complexity: O(4ⁿ · n).

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        if not digits:
            return []
        pad = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}
        res = []

        def bt(i, cur):
            if i == len(digits):
                res.append(cur)
                return
            for ch in pad[digits[i]]:
                bt(i + 1, cur + ch)

        bt(0, "")
        return res