Skip to content

Instantly share code, notes, and snippets.

@undrafted
Last active May 2, 2020 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save undrafted/9f3345c720aad22e892753616f494723 to your computer and use it in GitHub Desktop.
Save undrafted/9f3345c720aad22e892753616f494723 to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/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.
// 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:
// Input: "23"
// Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
// Note:
// Although the above answer is in lexicographical order, your answer could be in any order you want.
const phoneButtons: { [key in string]: string[] } = {
"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"],
};
var letterCombinations = function (digits: string) {
if (digits.length < 1) {
return [];
}
const combinations: string[] = [];
const digitsArray = digits.split("");
const getCharacters = (digitsArray: string[] = [], combination = "") => {
if (digitsArray.length < 1) {
combinations.push(combination);
return;
}
phoneButtons[digitsArray[0]].forEach((c) => {
getCharacters(digitsArray.slice(1), `${combination}${c}`);
});
};
getCharacters(digitsArray);
return combinations;
};
console.log(letterCombinations("234"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment