Letter Combinations of a Phone Number [Medium]

22 Sep 2026 2 min read
0
The Letter Combinations of a Phone Number problem requires generating all possible letter combinations that can be formed from a given string of digits.

Problem

Given a string digits containing digits from 2 to 9, return all possible letter combinations that the number could represent.

Each digit maps to a set of letters, similar to the keys on a traditional phone keypad. The order of the combinations does not matter.

Example(s)

Consider the following examples to understand the expected input and output.

Example 1

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

Example 2

Input
digits = ""
Output
[]

Solution

This solution uses the Backtracking pattern. We build the combination one digit at a time and try every letter mapped to the current digit.

When we have processed all digits, the current combination is complete, so we add it to the result. After exploring one letter, we remove it and try the next letter.
class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<>();

        if (digits.length() == 0) {
            return result;
        }

        String[] letters = {
            "", "", "abc", "def", "ghi",
            "jkl", "mno", "pqrs", "tuv", "wxyz"
        };

        backtrack(digits, 0, "", letters, result);

        return result;
    }

    private void backtrack(String digits, int i, String current,
                           String[] letters, List<String> result) {
        // All digits have been processed.
        if (i == digits.length()) {
            result.add(current);
            return;
        }

        String chars = letters[digits.charAt(i) - '0'];

        // Try every letter mapped to the current digit.
        for (char c : chars.toCharArray()) {
            backtrack(digits, i + 1, current + c, letters, result);
        }
    }
}

Complexity

Each digit can have up to 4 possible letters, so there can be up to 4n combinations. Since each combination contains n characters, the time complexity is O(4n × n).

The recursion uses O(n) stack space, excluding the space required to store the generated combinations. Including the output, the space complexity is O(4n × n).
Nagesh Chauhan

Nagesh Chauhan

Principal Software Engineer • Java • Python • Distributed Systems • AI/ML

Principal Software Engineer with 14+ years of experience designing and delivering large-scale distributed systems, cloud-native applications, and AI-powered platforms.

Passionate about solving complex engineering problems using strong data structures and algorithms, along with expertise in Java, Spring Boot, Python, System Design, Microservices, Cloud, Kafka, Elasticsearch, and Generative AI.

Share this Article

💬 Comments

Join the Discussion