Letter Combinations of a Phone Number in TypeScript

function letterCombinations(digits: string): string[] {
    // Base case: return an empty array if digits is empty
    if (digits.length === 0) return [];

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

    // This function will be used for backtracking
    function backtrack(index: number, path: string[]): void {
        // When the path's length equals the digits length, we've found a combination
        if (path.length === digits.length) {
            combinations.push(path.join(''));
            return;
        }

        // Get the letters that the current digit maps to, and loop through them
        const possibleLetters = phoneMap[digits[index]];
        for (let letter of possibleLetters) {
            // Add the letter to our current path and backtrack
            path.push(letter);
            backtrack(index + 1, path);
            // Backtrack: remove the last letter before moving onto the next
            path.pop();
        }
    }

    // Initialize an array to hold all combinations
    let combinations: string[] = [];

    // Begin the backtracking process
    backtrack(0, []);

    return combinations;
}

PrevNext