Letter Combinations of a Phone Number

List every string of letters that a phone number's digits can spell on a keypad.

Given a string digits made of the digits 2 to 9, return every string of letters the number could spell on a phone keypad, with one letter for each digit. The keypad maps 2 to "abc", 3 to "def", 4 to "ghi", 5 to "jkl", 6 to "mno", 7 to "pqrs", 8 to "tuv" and 9 to "wxyz". The strings can come in any order.

Example 1
Input: digits = "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
Example 2
Input: digits = ""
Output: []
Solution

The Idea

Older phones print letters on the number keys: the 2 key carries a, b and c, the 3 key carries d, e and f, and so on up to 9, which carries w, x, y and z. Typing 2 and then 3 could mean any letter from the 2 key followed by any letter from the 3 key.

Walk through Example 1 that way. Pick a for the 2, and the 3 can add d, e or f: ad, ae, af. Pick b for the 2 and you get bd, be, bf, and c gives cd, ce, cf. That is 3 ร— 3 = 9 strings, the nine in the output.

For two digits, two for loops, one inside the other, would list them. But "234" would need three loops, and a ten-digit number ten. A Java method has a fixed number of loops written into it, so how can one method handle any number of digits?

Look at the picture below. It shows every choice for "23" as a tree. The top box, labelled empty, is the start, before any letter is chosen. The row labelled "letter for 2" holds a, b and c, and under each of them the row labelled "letter for 3" holds the three ways to finish.

The choice tree for the digits 23. From empty, choose a letter for 2: a, b or c. Under each, choose a letter for 3: d, e or f. The path from empty to a to ad is highlighted, then d is taken back and e is tried. The bottom row holds the 9 combinations.

Follow the orange path: from empty, add a, then add d, and you reach ad, a full combination. Now step back up. The dashed arrow, labelled "take back d, try e", removes the d and adds e instead, which gives ae. After f, the a is taken back too, and b gets its turn.

Going down one row per digit, and stepping back up to try the next letter, is called backtracking. In this problem no branch is ever cut short: every letter goes with every other, so every path reaches the bottom row.

The tree also answers the question about loops. Each row needs the same work: try each letter of one digit, and for each letter, fill in the rows below. So the method that fills the row labelled "letter for 2" can call itself to fill the row labelled "letter for 3". A method that fills one row by calling itself for the row below is called recursive, and the number of calls waiting inside one another grows with the number of digits, while the code stays the same.

Solution Approach

Turning the tree into code means settling three things: how to find a digit's letters, how one call moves down a row and back up, and what to return when there are no digits.

Finding a digit's letters

Where do the letters of a digit come from? An array of ten strings, KEYS, holds the letters of each key at the position of its digit, so KEYS[2] is "abc" and KEYS[7] is "pqrs". Positions 0 and 1 hold empty strings, because those keys carry no letters.

The digit itself comes from the string as a char, such as '2', and Java stores that character as the number 50. Subtracting '0', which is 48, turns it into the position 2. Without the subtraction, "23" stops with ArrayIndexOutOfBoundsException: Index 50 out of bounds for length 10.

Moving down a row and back up

How does one call know where it is in the tree? It gets index, the position of the digit it should fill, and a StringBuilder named sb that holds the letters chosen so far. For each letter of that digit, it appends the letter, calls itself with index + 1, and then deletes the letter again.

That last delete is the step back up the tree. All calls share one sb, so without it the letters pile up: the second string comes out as ade instead of ae. When index equals the number of digits, every digit has its letter, and the call copies sb into the answer with toString().

An empty string of digits

What should "" give? Example 2 says an empty list. Left to the recursion, the first call would find index 0 equal to the length 0 and record sb as it is: a list holding one empty string. So the method checks for an empty input first and returns the empty list straight away.

Java Solution

The method letterCombinations and its helper build work in these steps:

  1. First, create the list result. If digits is empty, return it right away, still empty.
  2. Otherwise, call build(digits, 0, new StringBuilder(), result). The 0 is index, the first digit, and the new, empty sb is the box labelled empty.
  3. Inside build, if index equals digits.length(), add sb.toString() to result and return.
  4. Otherwise, look up the letters of the digit at index with KEYS[digits.charAt(index) - '0'] and loop over them. For each letter, append it to sb, call build with index + 1, and then delete the last character of sb.
  5. When the first call to build returns, result holds every combination, and letterCombinations returns it.

The main method runs both examples, the single digit 7, the digits 79 whose keys both carry four letters, and "234", for which it prints only the count.

Java
import java.util.ArrayList;
import java.util.List;

public class LetterCombinations {

    private static final String[] KEYS = {
        "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
    };

    public static List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<>();
        if (digits.isEmpty()) {
            return result;                    // no digits: no combinations, not [""]
        }
        build(digits, 0, new StringBuilder(), result);
        return result;
    }

    private static void build(String digits, int index, StringBuilder sb, List<String> result) {
        if (index == digits.length()) {
            result.add(sb.toString());        // one letter per digit: a full combination
            return;
        }
        for (char letter : KEYS[digits.charAt(index) - '0'].toCharArray()) {
            sb.append(letter);                // choose a letter for this digit
            build(digits, index + 1, sb, result);
            sb.deleteCharAt(sb.length() - 1); // take it back before the next letter
        }
    }

    public static void main(String[] args) {
        System.out.println(letterCombinations("23"));
        System.out.println(letterCombinations("").size() + " combinations for \"\"");
        System.out.println(letterCombinations("7"));
        System.out.println(letterCombinations("79"));
        System.out.println(letterCombinations("234").size() + " combinations for \"234\"");
    }
}

Running it prints:

Output
[ad, ae, af, bd, be, bf, cd, ce, cf]
0 combinations for ""
[p, q, r, s]
[pw, px, py, pz, qw, qx, qy, qz, rw, rx, ry, rz, sw, sx, sy, sz]
27 combinations for "234"

Look at the first line: [ad, ae, af, bd, be, bf, cd, ce, cf] is the bottom row of the tree, read from left to right, because each call tries its letters in key order. For the empty input, main prints the size, 0, because a list holding one empty string would also print as [].

The single 7 gives [p, q, r, s], one string per letter on its key. With "79", both keys carry four letters, so the fourth line has 4 ร— 4 = 16 strings, from pw to sz. The last line shows 27 for "234", which is 3 ร— 3 ร— 3.

Complexity

The work is one call to build for each box in the tree, plus copying each string of the bottom row into result.

  • Time: O(4n ยท n) for n digits, because each key carries at most four letters, so the bottom row holds at most 4n strings, and copying each one out of sb takes n steps. For "23", a counting run shows 13 calls: 1 for empty, 3 for the row of a, b and c, and 9 for the bottom row.
  • Space: O(n) besides the output, because the chain of calls is at most n + 1 deep, one call per row of the tree, and sb never holds more than n letters.