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.
digits is empty, return []."2": "abc", "3": "def", and so on).backtrack(index): if index == len(digits), record "".join(path).digits[index]: append the letter, recurse with backtrack(index + 1), then pop.backtrack(0) and return the result.Time: O(4ⁿ · n) — Space: O(n) recursion depth
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 resultHow the solution above works, piece by piece.
[""]).mapping gives each digit's letters, as on a phone keypad.backtrack(index) chooses a letter for digits[index]. When every digit has a letter, join path into a string.The recursion tree for digits = "23":