Skip to content

[LeetCode] 17. Letter Combinations of a Phone Number

Published: at 03:00 AM (2 min read)

Table of Contents

Open Table of Contents

Description

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent. Return the answer in any order.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

LeetCode 17. Letter Combinations of a Phone Number

Example 1:

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

Example 2:

Input: digits = ""
Output: []

Example 3:

Input: digits = "2"
Output: ["a","b","c"]

Constraints:

Approach

We build the letter combinations sequentially by iterating through the input digits and appending the corresponding letters for each digit to the combinations generated so far.

This results in all possible letter combinations for the input digit string.

Solution

/**
 * @param {string} digits
 * @return {string[]}
 */
var letterCombinations = function (digits) {
  // Map digits to corresponding letters
  const charMap = {
    2: ["a", "b", "c"],
    3: ["d", "e", "f"],
    4: ["g", "h", "i"],
    5: ["j", "k", "l"],
    6: ["m", "n", "o"],
    7: ["p", "q", "r", "s"],
    8: ["t", "u", "v"],
    9: ["w", "x", "y", "z"],
  };

  // Use reduce to accumulate letter combinations for each digit
  return [...digits].reduce((combinations, digit) => {
    const chars = charMap[digit];

    // If the digit is not in the map, skip processing it
    if (!chars) return combinations;

    // If there are no combinations yet, start with the current digit's letters
    if (!combinations.length) return charMap[digit];

    // For every existing combination, append each character from the current digit.
    return combinations.reduce(
      (acc, combination) => [...acc, ...chars.map(char => combination + char)],
      []
    );
  }, []);
};

Complexity Analysis

Time Complexity

The time complexity is O(3m×4n)O(3^m \times 4^n), where mm is the number of digits that map to 3 letters (e.g., 2, 3, 4, 5, 6, 8) and nn is the number of digits that map to 4 letters (e.g., 7, 9). The total number of combinations is the product of the number of letters for each digit.

Space Complexity

The space complexity is O(3m×4n)O(3^m \times 4^n), where mm is the number of digits that map to 3 letters and nn is the number of digits that map to 4 letters. The space complexity is determined by the number of possible combinations.


Previous Post
[Tool] yt-dlp 常用的影片類型與下載工具指令應用指南
Next Post
[Firefox] drag 事件 client/page 與 offset 等座標位置不正常運作