Letter Combinations of a Phone Number
On a phone keypad, each digit from 2 to 9 maps to a few letters:
2: abc 3: def 4: ghi 5: jkl 6: mno 7: pqrs 8: tuv 9: wxyz
Given a string digits containing only digits from 2 to 9, return every letter string the digits could spell, taking one letter for each digit. Return the strings in any order. If digits is empty, return an empty list.
Example 1
Input: digits = "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
Each of the three letters for 2 pairs with each of the three letters for 3.
Example 2
Input: digits = "" Output: []
Constraints
0 <= digits.length <= 4- Each character of
digitsis a digit from2to9.
Approach
Every answer picks one letter for the first digit, one for the second and so on. That's a nested loop with one level per digit, and recursion gives you a nested loop whose depth matches the input.
Keep the letters chosen so far. At position i, loop over the letters for digits[i]: add one, recurse to position i + 1, then remove it so the next letter can take its place. When i reaches the end of digits, the chosen letters form a complete combination, so add it to the result. An empty input has no combinations, so return an empty list up front instead of a list holding one empty string.
Steps
- If
digitsis empty, return an empty list. - Define
build(i). Ifiequals the length ofdigits, save the current letters as a string and return. - Otherwise, for each letter mapped to
digits[i], append it, callbuild(i + 1)and remove it. - Call
build(0)and return the result.
from typing import List
KEYS = {"2": "abc", "3": "def", "4": "ghi", "5": "jkl", "6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"}
def letter_combinations(digits: str) -> List[str]:
if not digits:
return []
result = []
letters = [] # the combination built so far
def build(i):
if i == len(digits):
result.append("".join(letters))
return
for ch in KEYS[digits[i]]:
letters.append(ch)
build(i + 1)
letters.pop() # undo the choice before trying the next letter
build(0)
return resultComplexity
- Time:
O(4^n * n), wherenis the length ofdigits. A digit maps to at most 4 letters, and each combination takesO(n)to copy into a string. - Space:
O(n)for the recursion and the letters being built, not counting the output.
Common mistakes
- Returning
[""]for an empty input. Zero digits means zero combinations here. - Forgetting that
7and9map to four letters, not three. - Building a new string at every level instead of appending and removing one character, which adds extra copying.