Skip to problem
←

Letter Combinations of a Phone Number

Medium 0 attempts

Given a string digits containing only digits from 2 through 9, return every string formed by choosing exactly one letter for each digit, in the same order as the input digits.

Use this telephone keypad mapping:

Digit Letters Digit Letters
2 abc 6 mno
3 def 7 pqrs
4 ghi 8 tuv
5 jkl 9 wxyz

Return each combination once, in any order. For an empty input, return [].

For example, "23" produces "ad" by choosing a for 2 and d for 3. It cannot produce "da", because the digit order must be preserved. Repeated digits represent separate choices: "22" can produce "aa", "ab", and so on.

Function contract

Implement letterCombinationsOfAPhoneNumber(digits). The argument is a string containing zero to four digits from 2 through 9.

Output: Return an array of distinct strings, with one mapped letter per input digit in input order. Return [] for empty input. Array ordering is ignored.

Example 1

Input
digits = "23"
Output
["ad","ae","af","bd","be","bf","cd","ce","cf"]

Example 2

Input
digits = ""
Output
[]
Constraints
  • 0 <= digits.length <= 4
  • digits[i] is in range ['2', '9']

Approach: Backtracking

Choose one mapped letter at each position. Keep the current choices in a shared path buffer, then join them into a string when every digit has been processed. Backtrack by removing the last choice before trying the next letter. Return an empty array immediately for empty input.

javascript
function letterCombinationsOfAPhoneNumber(digits) {
  if (!digits.length) return [];
  const letters = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"];
  const result = [];
  const path = [];

  function visit(index) {
    if (index === digits.length) {
      result.push(path.join(""));
      return;
    }
    for (const letter of letters[Number(digits[index])]) {
      path.push(letter);
      visit(index + 1);
      path.pop();
    }
  }

  visit(0);
  return result;
}

Let n be the number of digits and C the product of their mapped letter counts. For nonempty input, there are exactly C results; C is at most 4^n.

Time Complexity: O(n × C), including construction of the output strings.

Space Complexity: O(n) auxiliary space for the shared path and recursion, plus O(n × C) for the output. Empty input takes O(1) time and space.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript