Letter combinations
Intermediate · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Letter combinations means taking several groups of choices, like the letters on each phone key, and listing every way to pick one from each group. You pick from the first group, then the next, and when you reach the end you have a full answer. It is the "one from each box" pattern.
Practical use cases
- Web app: Vanity number finder. A business signup page offers customers a phone number that spells a word, like 2-2-5-5 for "CALL". The code takes each digit's letters and builds every possible letter string, then keeps those that appear in a dictionary. A 4-digit number gives only a few hundred strings, so results show up instantly.
- Web app: Product variant generator. An admin adds a T-shirt with 3 sizes, 4 colours and 2 fits and wants a list of every variant for the stock table. Picking one value from each attribute gives 24 variants. The same code works if someone later adds a fifth attribute, with no new loops. The admin no longer types 24 rows by hand.
- System: T9 keypads and autocomplete candidates. Old phone keyboards guessed your word by trying every letter combination for the digits you pressed, then checking a word list. Test-case generators use the same idea to produce every mix of options. Even a short keypad entry can expand to dozens of candidates, so the dictionary check that follows is what turns raw combinations into useful suggestions.
The story: Grandpa's Old Phone Keypad
Grandpa Bhaskar still owned a push-button phone from the old days. Mira noticed tiny letters under each number: 2 had ABC, 3 had DEF, and so on. "Grandpa, why letters on a number pad?" "We used them to remember numbers, and to type messages," he laughed.
Back then, typing 2 then 3 could mean AD, AE, AF, BD, BE, BF, CD, CE or CF. Nine possibilities for just two key presses! Mira asked how a phone could ever list all of them without missing one.
Grandpa drew a tree. "Start with the first key. Choose one of its letters. Then move to the next key and choose one of its letters. When you have used every key, you have a word. Then go back to the last key, choose the next letter, and so on."
That is backtracking with one choice per position: the position is the key, the choices are its letters. Mira wrote a tiny program, and for "23" it printed all nine words exactly once.
How to spot this problem, and where you need it
You have several groups of options and need every result made by picking exactly one option from each group, in order.
Signs you need it
- The problem lists categories, keys or attributes and asks for "all possible combinations", one from each.
- You are nesting loops, one per category, and adding a new category means editing the code.
- The number of results is the product of the group sizes, for example 3 times 4 times 2.
Where to use it in a project
- Creating all variants (size, colour, material) of a product for an inventory table.
- Generating all test combinations of browser, language and plan type for QA.
The solution
Keep the groups in a list and a position counter. At position 0, loop through the options in the first group, add one to your partial answer, and move to position 1. When the position passes the last group, the partial answer is a full combination, so save it. Then remove the last choice and try the next option. This one small recursive function replaces any number of nested loops.
Payoff: Before: a new nested loop for every attribute. After: one function making all 24 variants, still working when you add a fifth attribute.
Explain it like I am 8
Each button on the old phone owns a few letters. Pick one letter from the first button, then one letter from the next. When you run out of buttons you have a word. Go back and swap the last letter for its neighbour, and you get the next word, until no swaps are left.
How it works, step by step
- Map each digit to its letters, for example
2 → "abc",3 → "def". Handle an empty input by returning an empty list. - Use the index
iof the digit we are deciding, and a path of letters chosen so far. - Base case: when
iequals the number of digits, join the path and save the word. - For each letter on digit
i: choose it (add to the path), explore digiti + 1, then un-choose (remove it).
The code in four languages
PHP
<?php
// All words a string of phone digits could spell.
function letterCombinations(string $digits): array {
if ($digits === '') return [];
$map = ['2' => 'abc', '3' => 'def', '4' => 'ghi', '5' => 'jkl',
'6' => 'mno', '7' => 'pqrs', '8' => 'tuv', '9' => 'wxyz'];
$result = [];
$path = '';
$explore = function (int $i) use (&$explore, &$result, &$path, $digits, $map) {
if ($i === strlen($digits)) { // every key has a letter
$result[] = $path;
return;
}
foreach (str_split($map[$digits[$i]]) as $letter) {
$path .= $letter; // choose
$explore($i + 1); // explore the next key
$path = substr($path, 0, -1); // un-choose
}
};
$explore(0);
return $result;
}
echo implode(' ', letterCombinations('23')) . "\n";JavaScript
// All words a string of phone digits could spell.
function letterCombinations(digits) {
if (digits === '') return [];
const map = { 2: 'abc', 3: 'def', 4: 'ghi', 5: 'jkl', 6: 'mno', 7: 'pqrs', 8: 'tuv', 9: 'wxyz' };
const result = [];
let path = '';
function explore(i) {
if (i === digits.length) { // every key has a letter
result.push(path);
return;
}
for (const letter of map[digits[i]]) {
path += letter; // choose
explore(i + 1); // explore the next key
path = path.slice(0, -1); // un-choose
}
}
explore(0);
return result;
}
console.log(letterCombinations('23').join(' '));Java
import java.util.*;
public class Main {
static final Map<Character, String> KEYS = Map.of(
'2', "abc", '3', "def", '4', "ghi", '5', "jkl",
'6', "mno", '7', "pqrs", '8', "tuv", '9', "wxyz");
// All words a string of phone digits could spell.
static List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<>();
if (digits.isEmpty()) return result;
explore(digits, 0, new StringBuilder(), result);
return result;
}
static void explore(String digits, int i, StringBuilder path, List<String> result) {
if (i == digits.length()) { // every key has a letter
result.add(path.toString());
return;
}
for (char letter : KEYS.get(digits.charAt(i)).toCharArray()) {
path.append(letter); // choose
explore(digits, i + 1, path, result); // explore the next key
path.deleteCharAt(path.length() - 1); // un-choose
}
}
public static void main(String[] args) {
System.out.println(String.join(" ", letterCombinations("23")));
}
}Go
package main
import (
"fmt"
"strings"
)
var keys = map[byte]string{
'2': "abc", '3': "def", '4': "ghi", '5': "jkl",
'6': "mno", '7': "pqrs", '8': "tuv", '9': "wxyz",
}
// letterCombinations returns all words a string of phone digits could spell.
func letterCombinations(digits string) []string {
if digits == "" {
return nil
}
var result []string
path := ""
var explore func(i int)
explore = func(i int) {
if i == len(digits) { // every key has a letter
result = append(result, path)
return
}
for _, letter := range keys[digits[i]] {
path += string(letter) // choose
explore(i + 1) // explore the next key
path = path[:len(path)-1] // un-choose
}
}
explore(0)
return result
}
func main() {
fmt.Println(strings.Join(letterCombinations("23"), " "))
}Time: O(4^n × n) · Extra space: O(n). Each key has at most 4 letters, so answers multiply by up to 4 per digit. Joining each word costs n.
Watch out for
- Returning
[""]for empty input. Most problems want an empty list. - Treating the digits as one big number and looping over letters of all digits at once. The choice is per position.
- Forgetting that 7 and 9 have four letters, so a fixed "3 per key" loop is wrong.
Quick check
- How many words for the digits "23"?
- 5
- 6
- 9
- 12
- What is the base case?
- Index equals the number of digits
- Path is empty
- The digit is 0
- Digits "79" (4 letters each). How many words?
- 8
- 12
- 16
- 24