Skip to content

Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent on a traditional phone keypad.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

2 → "abc"
3 → "def"
4 → "ghi"
5 → "jkl"
6 → "mno"
7 → "pqrs"
8 → "tuv"
9 → "wxyz"
InputOutputExplanation
"23"["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]2 maps to “abc”, 3 maps to “def”; all pairings
""[]Empty input yields empty result
"2"["a", "b", "c"]Single digit maps directly to its letters
"234"27 combinations3 × 3 × 3 = 27 total combinations
  • 0 <= digits.length <= 4
  • digits[i] is a digit in the range ['2', '9']
ApproachTimeSpaceReturnsBest When
Backtracking (Recursive)O(4^n)O(4^n)All combinationsWant clear recursive structure, understanding decision tree
BFS (Iterative)O(4^n)O(4^n)All combinationsPrefer iterative approach, level-by-level exploration
  • Pick Backtracking if you are learning recursion and decision trees.
  • Pick BFS if you prefer iterative solutions or want to see level-by-level growth.
Most Common
Backtracking
O(4^n) time · O(4^n) space
Iterative
BFS
O(4^n) time · O(4^n) space
★ Recommended

Build combinations by recursively appending letters. For each digit, try all letters it maps to, then recurse on the next digit. When all digits are processed, save the combination.

The key insight is that we make a choice at each digit (which letter to use) and then recursively solve the subproblem for the remaining digits.

⏱ Time O(4^n) 4^n combinations 💾 Space O(4^n) Result storage

Input: digits = "23"

DepthDigitCurrentAction
0”2"""Start backtracking
1”3""a”Process 2 → “a”, now explore 3
2-”ad”Process 3 → “d”, save “ad” ✓
2-”ae”Process 3 → “e”, save “ae” ✓
2-”af”Process 3 → “f”, save “af” ✓
1”3""b”Backtrack to 2 → “b”, now explore 3
2-”bd”Process 3 → “d”, save “bd” ✓
Continue for “c” + all letters in “def”
function letterCombinationsBacktracking(digits):
if digits is empty:
return []
phoneMap = {
"2": "abc", "3": "def", "4": "ghi", "5": "jkl",
"6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"
}
result = []
function backtrack(index, current):
if index == len(digits):
result.append(current)
return
digit = digits[index]
letters = phoneMap[digit]
for letter in letters:
backtrack(index + 1, current + letter)
backtrack(0, "")
return result
letter_combinations_backtracking.py
from typing import List
def letter_combinations_backtracking(digits: str) -> List[str]:
"""
Generate all letter combinations using backtracking (recursive).
Time: O(4^n), Space: O(4^n) for result
"""
if not digits:
return []
phone_map = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz",
}
result = []
def backtrack(index: int, current_combination: str) -> None:
# Base case: we've processed all digits
if index == len(digits):
result.append(current_combination)
return
# Get the letters that the current digit maps to
current_digit = digits[index]
letters = phone_map[current_digit]
# Try each letter
for letter in letters:
backtrack(index + 1, current_combination + letter)
backtrack(0, "")
return result
print(letter_combinations_backtracking("23")) # ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
print(letter_combinations_backtracking("")) # []
print(letter_combinations_backtracking("2")) # ["a", "b", "c"]
🎯 Interview Favourite

Build combinations iteratively, processing one digit at a time. Start with a queue containing an empty string. For each digit, create new combinations by appending each of its letters to all current combinations.

This approach grows the result level by level, making it intuitive for those who prefer iterative over recursive solutions.

⏱ Time O(4^n) 4^n combinations 💾 Space O(4^n)

Input: digits = "23"

DigitQueue BeforeQueue AfterAction
”2”[""]["a", "b", "c"]Append each of “abc” to ""
"3”["a", "b", "c"]["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]Append each of “def” to each in queue
function letterCombinationsBFS(digits):
if digits is empty:
return []
phoneMap = {
"2": "abc", "3": "def", "4": "ghi", "5": "jkl",
"6": "mno", "7": "pqrs", "8": "tuv", "9": "wxyz"
}
queue = [""]
for digit in digits:
newQueue = []
letters = phoneMap[digit]
for current in queue:
for letter in letters:
newQueue.append(current + letter)
queue = newQueue
return queue
letter_combinations_bfs.py
from typing import List
from collections import deque
def letter_combinations_bfs(digits: str) -> List[str]:
"""
Generate all letter combinations using BFS (iterative).
Time: O(4^n), Space: O(4^n) for result
"""
if not digits:
return []
phone_map = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wxyz",
}
# Start with an empty combination
queue = deque([""])
for digit in digits:
size = len(queue)
letters = phone_map[digit]
# Process all current combinations
for _ in range(size):
current = queue.popleft()
# Create a new combination for each letter
for letter in letters:
queue.append(current + letter)
return list(queue)
print(letter_combinations_bfs("23")) # ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
print(letter_combinations_bfs("")) # []
print(letter_combinations_bfs("2")) # ["a", "b", "c"]
✓ Simple

A third approach demonstrating an alternative technique for solving this problem. This implementation optimizes either time or space complexity compared to the previous approaches.

⏱ Time O(n) Optimized complexity 💾 Space O(1) Efficient space usage
function approach3():
// Implementation approach goes here
letter_combinations_of_a_phone_number_space_optimized.py
"""
Solution for Letter Combinations of a Phone Number
"""
def solve():
"""Implementation for approach 3 of Letter Combinations of a Phone Number"""
pass
if __name__ == "__main__":
print("Solution ready")