Python coding

Words a phone keypad can spell

On an old phone keypad each digit from 2 to 9 stands for a few letters: 2 → abc, 3 → def, 4 → ghi, 5 → jkl, 6 → mno, 7 → pqrs, 8 → tuv, 9 → wxyz. Given the string digits, return every string it can spell: one letter per digit, in the same order as the digits ("23" gives "ad", never "da"). The list itself may be in any order. If digits is empty there is nothing to spell: return an empty list.

0 ≤ len(digits) ≤ 4, and digits contains only the characters 2–9.

  • keypad_words("23") → ["ad","ae","af","bd","be","bf","cd","ce","cf"]
  • keypad_words("7") → ["p","q","r","s"]
  • keypad_words("") → []
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

This is backtracking over a tree: level i chooses one letter for digits[i]. Every path from the root down to depth len(digits) spells one answer, and each answer has exactly one path.

Hint 2

Grow one shared path: add a letter for the current digit, recurse on the next digit, then remove the letter. A path as long as digits is one answer. The empty input gives [], not [""].

Solution and why it works
pythonO(n·4ⁿ), n = len(digits) · O(n) recursion depth, beyond the output
LETTERS = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl",
           "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}


def keypad_words(digits: str) -> list[str]:
    if not digits:
        return []                        # no digit, no word: not [""]
    res, path = [], []

    def bt(i: int) -> None:
        if i == len(digits):
            res.append("".join(path))
            return
        for ch in LETTERS[digits[i]]:
            path.append(ch)              # choose
            bt(i + 1)                    # explore the next digit
            path.pop()                   # unchoose

    bt(0)
    return res

Each level fixes the letter for one digit, so a path of full length is one answer and every answer is reached exactly once: no pruning is needed, because every branch is part of the output. The cost is the output itself, up to 4ⁿ strings of length n, and no approach can beat that. The trap is the empty input: the search would record one empty string, but there is no word to spell, so return [] before searching.