w3resource

JavaScript: Letter combinations of a number

JavaScript Function: Exercise-13 with Solution

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.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/javascript-exercises/javascript-recursion-function-exercise-13.php