โ† Back to Index

๐Ÿ“š Letter Combinations of a Phone Number โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Letter Combinations of a Phone Number problem involves generating all possible letter combinations for a given string of digits (2-9) based on the mapping of a telephone keypad.

๐Ÿ“ž Keypad Mapping

Digit Letters
2a, b, c
3d, e, f
4g, h, i
5j, k, l
6m, n, o
7p, q, r, s
8t, u, v
9w, x, y, z

๐Ÿงฑ Pattern Template

Recursive Backtracking

class Solution {
    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.isEmpty()) return new ArrayList<>();

        String[] mapping = {
            "", "", "abc", "def", "ghi", "jkl",
            "mno", "pqrs", "tuv", "wxyz"
        };
        List<String> result = new ArrayList<>();
        backtrack(0, digits, new StringBuilder(), result, mapping);
        return result;
    }

    private void backtrack(int index, String digits, StringBuilder current, List<String> result, String[] mapping) {
        if (index == digits.length()) {
            result.add(current.toString());
            return;
        }

        String letters = mapping[digits.charAt(index) - '0'];
        for (char letter : letters.toCharArray()) {
            current.append(letter);
            backtrack(index + 1, digits, current, result, mapping);
            current.deleteCharAt(current.length() - 1); // Backtrack
        }
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example

Input: digits = "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]

Explanation:
- Digit '2' maps to ['a', 'b', 'c'].
- Digit '3' maps to ['d', 'e', 'f'].
- Combine all possible pairs.

๐ŸŽฅ Animation

Watch the animation for this problem: Letter Combinations Animation

๐Ÿ’ก Pro Tips