Letter Combinations of a Phone Number Visualizer & Step-by-Step Algorithm Solution

Generate all possible letter combinations that the input phone digits could represent using keypad mapping and recursive backtracking.

Category: backtracking | Difficulty: Medium

Tags: Backtracking, Recursion, String, Decision Tree, Hash Table, LeetCode 17

Letter Combinations of a Phone Number

""
Combinations List
100%
state
digits"23"
n2
totalCombinations0
Start
1/80
Explanation

Start letterCombinations with digits = "23". Generate all combinations of letters mapped to these phone keypad digits.

Source Code
1function letterCombinations(digits: string): string[] {
2 const result: string[] = [];
3 const n = digits.length;
4 const numToChar: Record<string, string[]> = {
5 "2": ["a", "b", "c"],
6 "3": ["d", "e", "f"],
7 "4": ["g", "h", "i"],
8 "5": ["j", "k", "l"],
9 "6": ["m", "n", "o"],
10 "7": ["p", "q", "r", "s"],
11 "8": ["t", "u", "v"],
12 "9": ["w", "x", "y", "z"],
13 };
14 function backtrack(curr: string, index: number) {
15 if (curr.length === digits.length) {
16 result.push(curr);
17 return;
18 }
19 const chars = numToChar[digits[index]];
20 for (const char of chars) {
21 backtrack(curr + char, index + 1);
22 }
23 }
24
25 backtrack("", 0);
26 return result;
27}