Skip to main content

Letter Combinations of a Phone Number

Problem statement

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.

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:

  • 0 <= digits.length <= 4
  • digits[i] is a digit in the range ['2', '9'].

My solution

/**
* @param {string} digits
* @return {string[]}
*/
var letterCombinations = function(digits) {
const mappings = new Map([
["0", new Set()],
["1", new Set()],
["2", new Set(["a", "b", "c"])],
["3", new Set(["d", "e", "f"])],
["4", new Set(["g", "h", "i"])],
["5", new Set(["j", "k", "l"])],
["6", new Set(["m", "n", "o"])],
["7", new Set(["p", "q", "r", "s"])],
["8", new Set(["t", "u", "v"])],
["9", new Set(["w", "x", "y", "z"])],
]);
const results = [];
function walk(index, prefix) {
if (index >= digits.length) {
return results.push(prefix);
}
const digit = digits.charAt(index);
const nums = mappings.get(digit)

for (const char of nums.keys()) {
walk(index + 1, prefix + char)
}
}

if (digits.length > 0) {
walk(0, "")
}
return results;
};