Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions leet-code/17-letter-combinations-of-a-phone-number/README.md
Original file line number Diff line number Diff line change
@@ -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']`.
42 changes: 42 additions & 0 deletions leet-code/17-letter-combinations-of-a-phone-number/index.js
Original file line number Diff line number Diff line change
@@ -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;
};