Skip to content

Instantly share code, notes, and snippets.

@SCollinA
Created April 15, 2019 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SCollinA/f7c65a31e6145e8bd9386b798a1170ea to your computer and use it in GitHub Desktop.
Save SCollinA/f7c65a31e6145e8bd9386b798a1170ea to your computer and use it in GitHub Desktop.
get possible letter combinations from a string of digits 2-9 inclusive
/**
* @param {string} digits
* @return {string[]}
*/
// 2 = abc
// 3 = def
// 4 = ghi
// 5 = jkl
// 6 = mno
// 7 = pqrs
// 8 = tuv
// 9 = wxyz
var letterCombinations = function(digits) {
// given a string of unknown length
// containing digits 2-9
//assuming all chars are definitely digits and not 0 or 1
let letterCombos = []
let newLetterCombos = []
//probably use a hashmap
// map digits to chars
const digitMap = {
2: 'abc',
3: 'def',
4: 'ghi',
5: 'jkl',
6: 'mno',
7: 'pqrs',
8: 'tuv',
9: 'wxyz',
}
//for each digit in input string
for (let i = 0; i < digits.length; i++) {
// get possible chars
const possibleChars = digitMap[digits[i]]
// for each possible char
for (let j = 0; j < possibleChars.length; j++) {
const possibleChar = possibleChars[j]
// if no combos yet
if (!letterCombos.length) {
// add first digit's possible chars to start combo
newLetterCombos.push(possibleChar)
} else {
// for each existing letter combo
for (let k = 0; k < letterCombos.length; k++) {
// add this char to end of combo
newLetterCombos.push(letterCombos[k] + possibleChar)
}
}
}
// copy combos over to letter combos by ref
letterCombos = newLetterCombos
// reset newLetterCombos
newLetterCombos = []
}
// return phone number letter combos
return letterCombos
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment