Emmanuel Akinfulubi

JavaScriptRecursion

Letter combinations of a phone number in JavaScript

Advanced · 4 min read

Old phones had letters printed on the number keys, so a phone number could spell a word. This exercise asks the reverse question: given some digits, list every string of letters they could stand for. It is a famous interview problem, and it teaches one of the most useful recursive patterns there is: building every combination by choosing one option at a time.

In this tutorial you will write combinations(digits) so that '12' gives ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']. Along the way you will work out the digit-to-letter mapping from the expected output, which turns out to be the most important lesson here. You need to know strings, arrays, map and functions. Recursion and flatMap are explained below.

Read the test data first

The task's wording sounds like a phone keypad, where 2 is abc and 3 is def. But look at the expected answers:

  • '12' gives combinations starting with a, b and c, then d, e and f. So 1 must be abc and 2 must be def.
  • '9' gives just ['y', 'z']. So 9 is yz.

That isn't a phone keypad. It's the alphabet cut into groups of three: 1 is abc, 2 is def, and so on up to 9, which gets the two letters left over. When the description and the examples disagree, follow the examples, because they are what can be checked.

The recursive idea

Picture choosing one letter for each digit, from left to right. For '12', pick a letter for the 1 (a, b or c). Then, for each choice, stick it in front of every combination of the remaining digits, '2'.

So the combinations of '12' are: a, b or c, each followed by every combination of '2'. That is the same problem with one digit fewer. A function that solves a problem by calling itself on a smaller piece is recursive. When there are no digits left, there is nothing to combine, and the function stops. That stopping point is the base case.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

13 Every letter combination for a string of digits

hard

Each digit stands for a group of letters. Produce every combination, one letter taken from each digit's group. The test data: "12" gives ["ad","ae","af","bd","be","bf","cd","ce","cf"], and "9" gives ["y","z"].

Stuck? Three hints, smallest first
  1. 1. Work out the mapping from the expected output, not from the wording. Check what 1 and 9 must map to.
  2. 2. The base case is the empty string, and it needs care: returning an empty array is not the same as returning an array holding one empty string.
  3. 3. For each letter of the first digit, prefix it onto every combination of the rest.

Step 1: map a digit to its letters

Digit d gets the three letters starting at position (d - 1) × 3 of the alphabet. slice stops quietly at the end of a string, which is why 9 gets only two letters:

Step 1

const ALPHABET = 'abcdefghijklmnopqrstuvwxyz';
const lettersFor = (digit) => ALPHABET.slice((Number(digit) - 1) * 3, Number(digit) * 3);
console.log(lettersFor('1')); // 'abc'
console.log(lettersFor('2')); // 'def'
console.log(lettersFor('9')); // 'yz'

Number(digit) turns the character '2' into the number 2 before doing the math.

Step 2: map, then flatten

You need one more tool. map turns each item into something new. If each item becomes an array, you get an array of arrays. flatMap does the same, then flattens the result one level:

Step 2

const heads = ['a', 'b'];
const tails = ['d', 'e'];
console.log(heads.map((h) => tails.map((t) => h + t)));     // [ [ 'ad', 'ae' ], [ 'bd', 'be' ] ]
console.log(heads.flatMap((h) => tails.map((t) => h + t))); // [ 'ad', 'ae', 'bd', 'be' ]

That one line pairs every head with every tail. It's the heart of the solution.

Step 3: the recursive function

Take the letters for the first digit as the heads. Get the combinations for the rest of the digits as the tails. Then pair them up:

Step 3

const ALPHABET = 'abcdefghijklmnopqrstuvwxyz';
const lettersFor = (digit) => ALPHABET.slice((Number(digit) - 1) * 3, Number(digit) * 3);
function combinations(digits) {
  if (digits === '') return [];
  const heads = lettersFor(digits[0]).split('');
  const tails = combinations(digits.slice(1));
  if (tails.length === 0) return heads;
  return heads.flatMap((h) => tails.map((t) => h + t));
}
console.log(combinations('12')); // [ 'ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf' ]
console.log(combinations('9'));  // [ 'y', 'z' ]
console.log(combinations(''));   // []

digits.slice(1) is every digit after the first. For '12', the call for '2' gets tails from '', which are empty, so it returns its own letters ['d', 'e', 'f']. Then the call for '12' pairs a, b and c with those.

Step 4: the base case trap

Why the extra if (tails.length === 0) return heads? Try leaving it out:

JavaScript

const ALPHABET = 'abcdefghijklmnopqrstuvwxyz';
const lettersFor = (digit) => ALPHABET.slice((Number(digit) - 1) * 3, Number(digit) * 3);
function combosBroken(digits) {
  if (digits === '') return [];
  const heads = lettersFor(digits[0]).split('');
  const tails = combosBroken(digits.slice(1));
  return heads.flatMap((h) => tails.map((t) => h + t));
}
console.log(combosBroken('12')); // []

Pairing every head with no tails gives nothing. The empty result from the base case wipes out everything above it.

There is another fix: make the base case return [''], an array holding one empty string. Then the last digit pairs its letters with '' and keeps them. The catch is that combinations('') would then answer [''] instead of []. Both choices are reasonable. This solution keeps [] for empty input and handles the last digit with the extra check.

Step 5: count the results

Every digit with three letters multiplies the number of results by three:

Step 5

const ALPHABET = 'abcdefghijklmnopqrstuvwxyz';
const lettersFor = (digit) => ALPHABET.slice((Number(digit) - 1) * 3, Number(digit) * 3);
function combinations(digits) {
  if (digits === '') return [];
  const heads = lettersFor(digits[0]).split('');
  const tails = combinations(digits.slice(1));
  if (tails.length === 0) return heads;
  return heads.flatMap((h) => tails.map((t) => h + t));
}
console.log(combinations('123').length); // 27
console.log(combinations('129').length); // 18

3 × 3 × 3 is 27, and with the two-letter 9 it's 3 × 3 × 2, which is 18. The count grows fast: ten digits would give 59,049 strings.

The full solution

The panel has the alphabet mapping, the recursive combinations, and a real phone keypad version for contrast, with checks that pin down which mapping the task wants. Press Run to see the output.

The answer

// The mapping is derived from the expected output, which does NOT
// match a phone keypad. "12" -> "ad".. means 1 is 'abc' and 2 is 'def', and
// "9" -> ["y","z"] means 9 is 'yz'. That is the alphabet cut into threes:
// 1 abc, 2 def, 3 ghi, 4 jkl, 5 mno, 6 pqr, 7 stu, 8 vwx, 9 yz.
const ALPHABET = 'abcdefghijklmnopqrstuvwxyz';
const lettersFor = (digit) => ALPHABET.slice((Number(digit) - 1) * 3, Number(digit) * 3);

function combinations(digits) {
  if (digits === '') return [];                 // no digits, no combinations

  const heads = lettersFor(digits[0]).split('');
  const tails = combinations(digits.slice(1));

  // Last digit: the letters themselves are the answers.
  if (tails.length === 0) return heads;
  return heads.flatMap((h) => tails.map((t) => h + t));
}

// The real phone keypad, for contrast, since the prompt's wording implies it.
const KEYPAD = { 2: 'abc', 3: 'def', 4: 'ghi', 5: 'jkl', 6: 'mno', 7: 'pqrs', 8: 'tuv', 9: 'wxyz' };
const keypadCombos = (digits) => {
  if (digits === '') return [];
  const heads = KEYPAD[digits[0]].split('');
  const tails = keypadCombos(digits.slice(1));
  return tails.length === 0 ? heads : heads.flatMap((h) => tails.map((t) => h + t));
};

console.log("mapping: 1 ->", lettersFor('1'), ' 2 ->', lettersFor('2'), ' 9 ->', lettersFor('9'));
console.log('combinations("12") =', combinations('12'));
console.log('combinations("9")  =', combinations('9'));
console.log('how many for "123":', combinations('123').length, '= 3 x 3 x 3');
console.log('on a real keypad, "23" would be:', keypadCombos('23'));

Output


      
13 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 13 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

13 checks

test("the first case", combinations('12'), ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']);
test("the second case", combinations('9'), ['y', 'z']);
test('the mapping that produces it: 1 is abc', lettersFor('1'), 'abc');
test('2 is def', lettersFor('2'), 'def');
test('9 is the two left over', lettersFor('9'), 'yz');
test('no digits gives no combinations', combinations(''), []);
test('one digit gives its letters', combinations('3'), ['g', 'h', 'i']);
test('the count multiplies out', combinations('123').length, 27);
test('and with the short group', combinations('129').length, 18);
test('every result is as long as the input', combinations('123').every((c) => c.length === 3), true);
test('there are no duplicates', new Set(combinations('123')).size, 27);
test("a real keypad would give something different for '2'", keypadCombos('2'), ['a', 'b', 'c']);
test('which is not what the question asks for', combinations('2'), ['d', 'e', 'f']);

This one is really a lesson in reading a specification. The prompt says "digits ranging from 2 to 9", which is phone-keypad language, but the stated output uses digit 1 and maps 9 to just yz — that is the alphabet cut into groups of three, not a keypad. When the prose and the test data disagree, the test data is the specification, because it is the thing that can be checked. Both mappings are implemented above so the difference is visible, and the assertions pin down the version the question asks for.

The base case is the other trap. Returning [] for the empty string means the last digit has to be handled specially. Returning [''] instead makes the general case work all the way down, but then combinations('') answers [''] rather than []. Neither is wrong; you just have to pick one and test it.

Common mistakes

  • Assuming a phone keypad. On a keypad, 2 is abc. The expected output here needs 2 to be def.
  • Returning [] with no special case for the last digit. Every combination gets multiplied by nothing and the whole answer is empty.
  • Using map instead of flatMap. You get an array of arrays instead of one flat list of strings.

Try it yourself

  1. Switch combinations to use the real keypad, where 7 is pqrs and 9 is wxyz. How many results does '79' give?
  2. Change the base case to return [''] and remove the special case. What does combinations('') give now?
  3. Filter the results of combinations('123') to keep only those containing a vowel.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.