KatInterview

17. Letter Combinations of a Phone Number

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to generate all possible letter combinations for a given string of digits from 2 to 9. Each digit maps to a set of letters, similar to a standard telephone keypad. This is a classic combinatorial problem that can be solved by exploring all possible choices for each digit in a systematic way.

Solution

Letter Combinations of a Phone Number in Python

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        # Handle the edge case of an empty input string.
        if not digits:
            return []

        # Mapping of digits to letters.
        mapping = {
            '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
            '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'
        }

        result = []

        def backtrack(index: int, current_combination: str):
            # Base case: If the current combination's length equals the digits' length,
            # we have a complete combination.
            if index == len(digits):
                result.append(current_combination)
                return

            # Get the letters for the current digit.
            possible_letters = mapping[digits[index]]

            # Iterate through each possible letter and recurse.
            for letter in possible_letters:
                # Make a recursive call for the next digit with the new combination.
                backtrack(index + 1, current_combination + letter)

        # Start the backtracking process from the first digit (index 0).
        backtrack(0, "")
        return result

Letter Combinations of a Phone Number in Java

class Solution {
    private List<String> result = new ArrayList<>();
    private String[] mapping = {
        "", "", "abc", "def", "ghi", "jkl", 
        "mno", "pqrs", "tuv", "wxyz"
    };

    public List<String> letterCombinations(String digits) {
        // Handle the edge case of an empty input string.
        if (digits == null || digits.length() == 0) {
            return result;
        }
        // Start the backtracking process.
        backtrack(digits, new StringBuilder(), 0);
        return result;
    }

    private void backtrack(String digits, StringBuilder currentCombination, int index) {
        // Base case: if the combination is complete (length equals digits' length),
        // add it to the result list.
        if (index == digits.length()) {
            result.add(currentCombination.toString());
            return;
        }

        // Get the letters corresponding to the current digit.
        char digit = digits.charAt(index);
        String letters = mapping[digit - '0'];

        // Iterate through the letters and recurse.
        for (int i = 0; i < letters.length(); i++) {
            char letter = letters.charAt(i);
            
            // Append the letter and recurse for the next digit.
            currentCombination.append(letter);
            backtrack(digits, currentCombination, index + 1);
            
            // Backtrack: remove the last character to explore other paths.
            currentCombination.deleteCharAt(currentCombination.length() - 1);
        }
    }
}

Letter Combinations of a Phone Number in C++

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        // Handle the edge case of an empty input string.
        if (digits.empty()) {
            return {};
        }

        // Mapping of digits to letters.
        const vector<string> mapping = {
            "", "", "abc", "def", "ghi", "jkl", 
            "mno", "pqrs", "tuv", "wxyz"
        };

        vector<string> result;
        string currentCombination;
        // Start the backtracking process from the first digit (index 0).
        backtrack(0, currentCombination, digits, mapping, result);
        return result;
    }

private:
    void backtrack(int index, string& currentCombination, const string& digits, 
                   const vector<string>& mapping, vector<string>& result) {
        // Base case: If the current combination's length equals the digits' length,
        // we have a complete combination.
        if (index == digits.length()) {
            result.push_back(currentCombination);
            return;
        }

        // Get the letters corresponding to the current digit.
        // The digit character is converted to an integer to be used as an index.
        string letters = mapping[digits[index] - '0'];

        // Iterate through all possible letters for the current digit.
        for (char letter : letters) {
            // Add the letter to the current combination.
            currentCombination.push_back(letter);
            // Recursively call backtrack for the next digit.
            backtrack(index + 1, currentCombination, digits, mapping, result);
            // Backtrack: remove the last letter to explore other possibilities.
            currentCombination.pop_back();
        }
    }
};

Letter Combinations of a Phone Number in TypeScript

function letterCombinations(digits: string): string[] {
    // Handle the edge case of an empty input string.
    if (digits.length === 0) {
        return [];
    }

    // Mapping of digits to letters.
    const mapping: { [key: string]: string } = {
        '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl',
        '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'
    };

    const result: string[] = [];

    function backtrack(index: number, currentCombination: string) {
        // Base case: If we have processed all digits, we have a complete combination.
        if (index === digits.length) {
            result.push(currentCombination);
            return;
        }

        // Get the letters corresponding to the current digit.
        const letters = mapping[digits[index]];

        // Iterate through each letter and make a recursive call.
        for (const letter of letters) {
            // Explore the next digit with the appended letter.
            backtrack(index + 1, currentCombination + letter);
        }
    }

    // Start the backtracking process from the first digit (index 0).
    backtrack(0, "");
    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.