BackendML

Letter Combinations of a Phone Number

Medium2 min read
The Letter Combinations of a Phone Number problem requires generating all possible letter combinations that a given digit string can represent based on the letters mapped to each digit on a phone keypad.

Problem

Given a string of digits digits, return all possible letter combinations that the number could represent.

The mapping of digits to letters is the same as on a traditional telephone keypad. The input contains digits from 2 to 9.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

digits = "23"

Output

["ad","ae","af","bd","be","bf","cd","ce","cf"]

Solution

This solution uses Backtracking to build all possible letter combinations. For each digit, we iterate through all its corresponding letters and add one letter to the current combination.

The recursion then moves to the next digit. When the length of the current combination becomes equal to the length of the input, a complete combination has been formed and is added to the result.

After each recursive call, the last letter is removed so that the algorithm can explore the next possible letter for the current digit.
public List<String> letterCombinations(String digits) {
    List<String> result = new ArrayList<>();

    if (digits == null || digits.isEmpty()) {
        return result;
    }

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

    backtrack(digits, 0, new StringBuilder(), result, mapping);
    return result;
}

private void backtrack(String digits, int index,
        StringBuilder current, List<String> result,
        String[] mapping) {

    // A complete combination is found.
    if (index == digits.length()) {
        result.add(current.toString());
        return;
    }

    int digit = digits.charAt(index) - '0';
    String letters = mapping[digit];

    for (char letter : letters.toCharArray()) {
        // Choose the current letter.
        current.append(letter);

        // Process the next digit.
        backtrack(digits, index + 1, current, result, mapping);

        // Undo the choice.
        current.deleteCharAt(current.length() - 1);
    }
}

Complexity

Each digit can map to at most 4 letters. Therefore, for n digits, the algorithm can generate up to 4n combinations. Since each combination contains n characters, the time complexity is O(n × 4n).

The recursion depth is O(n), and the current combination requires O(n) space, excluding the space required for storing the output.

Comments

No comments yet. Ask a question or share what helped.