w3resource
w3resource logo

JavaScript: Letter combinations of a number

(追記) (追記ここまで)
(追記) (追記ここまで)

JavaScript Function: Exercise-13 with Solution

Letter Combinations from Digits

A string consists of digits ranging from 2 to 9, inclusive. Write a JavaScript program to get all possible letter combinations that represent the number using recursion.

Letter Combination:
1: 'abc',
2: 'def',
3: 'ghi',
4: 'jkl',
5: 'mno',
6: 'pqr',
7: 'stu',
8: 'vwx'
9: 'yz'

Test Data:
("12") -> ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
("9") -> ["y", "z"]

Sample Solution-1:

JavaScript Code:

// Function to generate letter combinations for a given digit string
const letterCombinations = (digits) => {
 const length = digits?.length; // Get the length of the input digits
 const result = []; // Initialize an array to store the combinations
 // Base case: If the input digits are empty, return an empty array
 if (!length) {
 return result;
 }
 // Map of digits to corresponding letters on a phone keypad
 const digitMap = {
 1: 'abc',
 2: 'def',
 3: 'ghi',
 4: 'jkl',
 5: 'mno',
 6: 'pqr',
 7: 'stu',
 8: 'vwx',
 9: 'yz',
 };
 // Recursive function to generate combinations
 const generateCombinations = (index, combination) => {
 let letter;
 let letterIndex;
 // If the index exceeds the length, add the combination to the result array
 if (index>= length) {
 result.push(combination);
 return;
 }
 // Get the letters corresponding to the current digit
 const digit = digitMap[digits[index]];
 // Iterate through each letter and recursively generate combinations
 letterIndex = 0;
 while ((letter = digit[letterIndex++])) {
 generateCombinations(index + 1, combination + letter);
 }
 };
 // Start generating combinations from the first digit
 generateCombinations(0, '');
 // Return the final array of combinations
 return result;
};
// Test the function with different input digits
console.log(letterCombinations("12")); // Output: ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
console.log(letterCombinations("9")); // Output: ['yw', 'yx', 'yy', 'zw', 'zx', 'zy']

Output:

["ad","ae","af","bd","be","bf","cd","ce","cf"]
["y","z"]

Flowchart:

Flowchart: JavaScript recursion function- Letter combinations of a number.

Live Demo:

See the Pen javascript-recursion-function-exercise-13 by w3resource (@w3resource) on CodePen.


Sample Solution-2:

JavaScript Code:

const letterCombinations = (digits) => {
 const digitMap = {
 1: 'abc',
 2: 'def',
 3: 'ghi',
 4: 'jkl',
 5: 'mno',
 6: 'pqr',
 7: 'stu',
 8: 'vwx',
 9: 'yz',
 };
 const backtrack = (index, currentCombination) => {
 if (index === digits.length) {
 result.push(currentCombination);
 return;
 }
 const currentDigit = digits[index];
 const letters = digitMap[currentDigit];
 for (const letter of letters) {
 backtrack(index + 1, currentCombination + letter);
 }
 };
 const result = [];
 if (digits) {
 backtrack(0, '');
 }
 return result;
};
// Test the function with different input digits
console.log(letterCombinations("12")); // Output: ['ad', 'ae', 'af', 'bd', 'be', 'bf', 'cd', 'ce', 'cf']
console.log(letterCombinations("9")); // Output: ['yw', 'yx', 'yy', 'zw', 'zx', 'zy']

Output:

["ad","ae","af","bd","be","bf","cd","ce","cf"]
["y","z"]

Flowchart:

Flowchart: JavaScript recursion function- Letter combinations of a number.

For more Practice: Solve these Related Problems:

  • Write a JavaScript function that recursively generates all letter combinations for a given digit string based on telephone keypad mapping.
  • Write a JavaScript function that returns all possible letter combinations from digits using recursion and backtracking.
  • Write a JavaScript function that handles edge cases such as empty input and invalid digits while generating letter combinations recursively.
  • Write a JavaScript function that recursively computes letter combinations for digits and removes any duplicate results.

Improve this sample solution and post your code through Disqus.

Previous: Binary Search Algorithm using recursion.
Next:Javascript Conditional Statements and Loops Exercises

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

(追記) (追記ここまで)


(追記) (追記ここまで)
(追記) (追記ここまで)


AltStyle によって変換されたページ (->オリジナル) /