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#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

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);
}
static final String[] MAP = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };

static void letters(String digits, int idx, String path, List<String> result) {
    if (idx == digits.length()) { result.add(path); return; }
    String chars = MAP[digits.charAt(idx) - '0'];
    if (chars.isEmpty()) { letters(digits, idx + 1, path, result); return; }
    for (int i = 0; i < chars.length(); i++)
        letters(digits, idx + 1, path + chars.charAt(i), result);
}
const vector<string> MAP = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

void letters(const string& digits, int idx, const string& path, vector<string>& result) {
    if (idx == (int)digits.size()) { result.push_back(path); return; }
    const string& chars = MAP[digits[idx] - '0'];
    if (chars.empty()) { letters(digits, idx + 1, path, result); return; }
    for (char ch : chars)
        letters(digits, idx + 1, path + ch, result);
}
MAP = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]

def letters(digits: str, idx: int, path: str, result: list[str]) -> None:
    if idx == len(digits): result.append(path); return
    chars = MAP[int(digits[idx])]
    if chars == "": letters(digits, idx + 1, path, result); return
    for ch in chars:
        letters(digits, idx + 1, path + ch, 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.