Skip to content

Instantly share code, notes, and snippets.

@bdthinh
Last active November 14, 2023 15:46
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 bdthinh/2080ad1f06177258688df0f912dd573c to your computer and use it in GitHub Desktop.
Save bdthinh/2080ad1f06177258688df0f912dd573c to your computer and use it in GitHub Desktop.
Question2: transformDigitsToLetters
// # 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 shown in file telephone.png.
// # 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"]
const multipleArrays = (array1, array2) => {
const product = [];
for (let i = 0; i < array1.length; i++) {
for (let j = 0; j < array2.length; j++) {
product.push(array1[i] + array2[j]);
}
}
return product;
};
const transformDigitsToLetters = digits => {
const digitToLetterDict = {
2: 'abc',
3: 'def',
4: 'ghi',
5: 'jkl',
6: 'mno',
7: 'pqrs',
8: 'tuv',
9: 'wxyz',
};
let result = [];
if (!digits) {
return [];
}
// assign result first letters from first digit
result = digitToLetterDict[digits[0]].split('');
// travel from second digit to end with slice(1)
digits
.split('')
.slice(1)
.forEach(digit => {
result = multipleArrays(result, digitToLetterDict[digit].split(''));
});
return result;
};
const result = transformDigitsToLetters('293');
console.log(`transformDigitsToLetters ${result}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment