diff --git a/leet-code/17-letter-combinations-of-a-phone-number/README.md b/leet-code/17-letter-combinations-of-a-phone-number/README.md new file mode 100644 index 0000000..fb921d3 --- /dev/null +++ b/leet-code/17-letter-combinations-of-a-phone-number/README.md @@ -0,0 +1,23 @@ +# 17-letter-combinations-of-a-phone-number + +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 digits 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']`. diff --git a/leet-code/17-letter-combinations-of-a-phone-number/index.js b/leet-code/17-letter-combinations-of-a-phone-number/index.js new file mode 100644 index 0000000..ce84af7 --- /dev/null +++ b/leet-code/17-letter-combinations-of-a-phone-number/index.js @@ -0,0 +1,42 @@ +/** + * @param {string} digits + * @return {string[]} + */ +var letterCombinations = function(digits) { + // store the distinct combinations of chracters + const combinations = []; + // short circuit if there are no digits to consider + if (digits === "") return combinations + // lookup alphabetic characters by number + const lettersByNumber = { + 2: 'abc', + 3: 'def', + 4: 'ghi', + 5: 'jkl', + 6: 'mno', + 7: 'pqrs', + 8: 'tuv', + 9: 'wxyz' + } + // explore all possible combinations using backtracking + function search(index, workingMemory) { + // combinations can't exceed the length of digits used + const isValidCombination = index === digits.length; + if (isValidCombination) { + // add the combination + combinations.push(workingMemory) + return; + } + // lookup the letters corresponding to the current number + const letters = lettersByNumber[digits[index]] + // add each character to working memory and continue searching for combinations + for (var j = 0; j < letters.length; j++) { + // increment the index to process the next digit + search(index + 1, workingMemory + letters[j]) + } + } + // start at the first digit and no working memory + search(0, "") + // return the alphabetic combinations + return combinations; +}; \ No newline at end of file