hectane logo

Find all possible combination of alphabets from a phone dial pad using javascript

Interview problem to generate all possible combinations of alphabets from a phone dial pad on number input

Find all possible combination of alphabets from a phone dial pad using javascript

Problem

Generate all combination of words that can possibly created using a 0-9 dial pad of a phone

This interview problem has been asked in coding rounds of multiple companies like google, amazon. This was once asked in Zalando’s live coding round for the role of frontend developer.

Solution

I solved this using a recursive solution.

The function accepts a digit string and then each words from phoneDigitsToLetters hash map is recursively looped and pushed to create each word. Once each word is completed then it's pushed to the words array.

/**
 * A function to convert digits to words of phone dial pad
 * @param {string} digitString
 */
function telephoneNumberWords (digitString) {
  // Hashmap of Phone dialpad to letters
  /**  @type {object}  */
  const phoneDigitsToLetters = {
    0: '0',
    1: '1',
    2: 'ABC',
    3: 'DEF',
    4: 'GHI',
    5: 'JKL',
    6: 'MNO',
    7: 'PQRS',
    8: 'TUV',
    9: 'WXYZ',
  };

  // make results array
  /** @type {Array<string>} */
  const words = [];

  // make inner recursive function (word, digitsLeft)
  /**
   * @param {string} word
   * @param {string} digits
   */
  function lettersForDigits(word, digits) {
    // base case: if no digits left, push word to results
    if (digits.length === 0) {
      return words.push(word);
    }
    // grab current digit from digitsLeft
    // for each letter option, add letter to word and recurse
    phoneDigitsToLetters[digits[0]].split('').forEach(function (letter) {
      lettersForDigits(word + letter, digits.slice(1));
    });
  }

  // invoke recursive function
  lettersForDigits('', digitString.split(''));

  // return results array
  return words;
};

const result = telephoneNumberWords('23');

// Logging the result
console.log(result);
//[ 'AD', 'AE', 'AF', 'BD', 'BE', 'BF', 'CD', 'CE', 'CF' ]