Algo-Sim › Recursion & Backtracking
Letter Combinations of a Phone Number
Medium · Recursion & Backtracking · step through it in Java, Python and C++ on your own input
Every string a phone number can spell: pick one letter per digit, depth by depth. The tree has one level per digit.
Problem
Given a string of digits from 2 to 9, return every letter combination the number could represent, using the letters on a phone keypad (2 → abc, 3 → def, …, 7 → pqrs, 9 → wxyz). Return them in any order; an empty input gives an empty list.
Constraints
- 0 ≤ digits.length ≤ 4
- digits[i] is in '2'–'9'
- At most 4⁴ = 256 combinations
Edge cases to test
- Empty input:
[], not[""] - Digits 7 and 9 have four letters
- One digit
Follow-up questions
- What is the cost?
- O(4ⁿ · n): up to four letters per digit, and each string costs n to build.
- Can it be iterative?
- Keep a list of prefixes and extend each with every letter of the next digit: BFS by level.
Solution
Java
private static final String[] KEYS = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> result = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if (digits.isEmpty()) return result;
backtrack(digits, 0, new StringBuilder());
return result;
}
void backtrack(String digits, int index, StringBuilder path) {
if (index == digits.length()) {
result.add(path.toString());
return;
}
for (char c : KEYS[digits.charAt(index) - '0'].toCharArray()) {
path.append(c);
backtrack(digits, index + 1, path);
path.deleteCharAt(path.length() - 1);
}
}Python
KEYS = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
def letter_combinations(digits):
if not digits:
return []
result = []
def backtrack(index, path):
if index == len(digits):
result.append("".join(path))
return
for c in KEYS[int(digits[index])]:
path.append(c)
backtrack(index + 1, path)
path.pop()
backtrack(0, [])
return resultC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<string> KEYS = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> result = {};
vector<string> letterCombinations(string &digits) {
if (digits.empty())
return result;
string path;
backtrack(digits, 0, path);
return result;
}
void backtrack(string &digits, int index, string &path) {
if (index == int(digits.size())) {
result.push_back(path);
return;
}
for (char c : KEYS[digits[index] - '0']) {
path.push_back(c);
backtrack(digits, index + 1, path);
path.pop_back();
}
}
};
More Recursion & Backtracking problems
- Fibonacci Number (Easy)
- Tower of Hanoi (Medium)
- Generate Parentheses (Medium)
- Subsets (Medium)
- Subsets II (Medium)
- Permutations (Medium)
- Permutations II (Medium)
- Combinations (Medium)
- Combination Sum (Medium)
- Combination Sum II (Medium)
- Palindrome Partitioning (Medium)
- Restore IP Addresses (Medium)
- Word Break II (Hard)
- Remove Invalid Parentheses (Hard)
- Word Search (Medium)
- N-Queens (Hard)
- Sudoku Solver (Hard)