Letter Combinations of a Phone Number

Every word a string of phone-keypad digits could spell, one letter per digit.

Time O(4ⁿ)Space O(n)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

Handle one digit at a time. Look up the letters that digit maps to, and for each one, append it to the path so far and recurse on the next digit. Once every digit has contributed a letter, the path is a complete word to record.

Code

static readonly string[] Map = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

public static void Letters(string digits, int idx, string path, List<string> result) {
    if (idx == digits.Length) { result.Add(path); return; }
    string letters = Map[digits[idx] - '0'];
    if (letters == "") { Letters(digits, idx + 1, path, result); return; }
    for (int i = 0; i < letters.Length; i++)
        Letters(digits, idx + 1, path + letters[i], result);
}

Tips

In the .NET library

Map[digits[idx] - '0'] turns a character digit straight into an array index. It is the same trick as bits[v.toString(2)] in reverse: subtracting the character code of '0' converts a digit character to its numeric value.