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

Velu S Gautam1 min readInterviews

Problem

Generate all combinations of words that can be created using a 0-9 dial pad of a phone

This interview problem has come up in coding rounds at several companies, including Google and Amazon. It was also asked in Zalando's live coding round for a frontend developer role.

Solution

I solved this with a recursive approach.

The function takes a digit string, then recursively loops through each letter from the phoneDigitsToLetters map, appending it to build up a word. Once a word is complete, it's pushed to the words array.

JAVASCRIPT
/**
 * 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' ]

Comments