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
Example 1
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
Example 2
Output: []
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"234"
Look at the picture below. It shows every choice for "23"
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, KEYSKEYS[2]KEYS[7]
The digit itself comes from the string as a char'2''0'"23"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 indexStringBuildersbindex + 1
That last delete is the step back up the tree. All calls share one sbadeaeindexsbtoString()
An empty string of digits
What should ""indexsb
Java Solution
The method letterCombinationsbuild
- First, create the list
. Ifresult is empty, return it right away, still empty.digits - Otherwise, call
. The 0 isbuild(digits, 0, new StringBuilder(), result) , the first digit, and the new, emptyindex is the box labelled empty.sb - Inside
, ifbuild equalsindex , adddigits.length() tosb.toString() and return.result - Otherwise, look up the letters of the digit at
withindex and loop over them. For each letter, append it toKEYS[digits.charAt(index) - '0'] , callsb withbuild , and then delete the last character ofindex + 1 .sb - When the first call to
returns,build holds every combination, andresult returns it.letterCombinations
The main"234"
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:
[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]main[]
The single 7 gives [p, q, r, s]"79"pwsz"234"
Complexity
The work is one call to buildresult
- 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
takes n steps. Forsb , a counting run shows 13 calls: 1 for empty, 3 for the row of a, b and c, and 9 for the bottom row."23" - 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
never holds more than n letters.sb