Typorithm · medium

Letter Combinations

▷ Interactive algorithm labletter-combinationsbacktrackingdigit-mapcartesian-productchoose-explore-undo
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Letter Combinations

0%

Backtracking

Map each phone digit to its letters and build every combination by choosing one letter per digit.

Each digit from 2 to 9 maps to a group of letters, like a phone keypad.

Backtracking advances digit by digit, appending each letter of the current digit's group and recursing.

Once index reaches the digit count, the path holds one full-length combination to record.

Preparing algorithm lab…
01

Map digits to letter groups.

02

Recurse one digit deeper per letter.

03

Record full-length combinations.

function letterCombinations(digits) {
  if (digits.length === 0) return [];

  const map = {
    2: "abc",
    3: "def",
    4: "ghi",
    5: "jkl",
    6: "mno",
    7: "pqrs",
    8: "tuv",
    9: "wxyz",
  };

  const result = [];

  function backtrack(index, path) {
    if (index === digits.length) {
      result.push(path.join(""));
      return;
    }

    const letters = map[digits[index]];
    for (const letter of letters) {
      path.push(letter);
      backtrack(index + 1, path);
      path.pop();
    }
  }

  backtrack(0, []);
  return result;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. All digits used

A combination is complete once every digit has contributed a letter.

if (index === digits.length)

2. Lookup group

Map the current digit to its group of letters.

const letters = map[digits[index]]

3. Try each letter

Branch on every letter the current digit offers.

for (const letter of letters)

4. Choose letter

Append the chosen letter to the growing combination.

path.push(letter)

5. Undo

Remove the letter to try the next one in the group.

path.pop()

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Letter Combinations: Visual Walkthrough & Practice · Typorithm | ApplyDjinn