Related Articles

# Print all possible words from phone digits

• Difficulty Level : Hard
• Last Updated : 02 Jul, 2021

Before the advent of QWERTY keyboards, texts and numbers were placed on the same key. For example, 2 has “ABC” if we wanted to write anything starting with ‘A’ we need to type key 2 once. If we wanted to type ‘B’, press key 2 twice and thrice for typing ‘C’. Below is a picture of such a keypad. Given a keypad as shown in the diagram, and an n digit number, list all words which are possible by pressing these numbers.

Example:

```Input number: 234
Output:
afi bdg bdh bdi beg beh bei bfg
bfh bfi cdg cdh cdi ceg ceh cei
cfg cfh cfi
Explanation: All possible words which can be
formed are (Alphabetical order):
afi bdg bdh bdi beg beh bei bfg
bfh bfi cdg cdh cdi ceg ceh cei
cfg cfh cfi
If 2 is pressed then the alphabet
can be a, b, c,
Similarly, for 3, it can be
d, e, f, and for 4 can be g, h, i.

Input number: 5
Output: j k l
Explanation: All possible words which can be
formed are (Alphabetical order):
j, k, l, only these three alphabets
can be written with j, k, l.```

Approach: It can be observed that each digit can represent 3 to 4 different alphabets (apart from 0 and 1). So the idea is to form a recursive function. Then map the number with its string of probable alphabets, i.e 2 with “abc”, 3 with “def” etc. Now the recursive function will try all the alphabets, mapped to the current digit in alphabetic order, and again call the recursive function for the next digit and will pass on the current output string.

Example:

```If the number is 23,

Then for 2, the alphabets are a, b, c
So 3 recursive function will be called
with output string as a, b, c respectively
and for 3 there are 3 alphabets d, e, f
So, the output will be ad, ae and af for
the recursive function with output string.
Similarly, for b and c, the output will be:
bd, be, bf and cd, ce, cf respectively.```

Algorithm:

1. Map the number with its string of probable alphabets, i.e 2 with “abc”, 3 with “def” etc.
2. Create a recursive function which takes the following parameters, output string, number array, current index, and length of number array
3. If the current index is equal to the length of the number array then print the output string.
4. Extract the string at digit[current_index] from the Map, where the digit is the input number array.
5. Run a loop to traverse the string from start to end
6. For every index again call the recursive function with the output string concatenated with the ith character of the string and the current_index + 1.

Implementation: Note that the input number is represented as an array to simplify the code.

## C++

 `// C++ program for the above approach` `#include ``using` `namespace` `std;` `// Function to find all possible combinations by``// replacing key's digits with characters of the``// corresponding list``void` `findCombinations(vector<``char``> keypad[],``                      ``int` `input[], string res, ``int` `index)``{``    ``// If processed every digit of key, print result``    ``if` `(index == -1) {``        ``cout << res << ``" "``;``        ``return``;``    ``}` `    ``// Stores current digit``    ``int` `digit = input[index];` `    ``// Size of the list corresponding to current digit``    ``int` `len = keypad[digit].size();` `    ``// One by one replace the digit with each character in the``    ``// corresponding list and recur for next digit``    ``for` `(``int` `i = 0; i < len; i++) {``        ``findCombinations(keypad, input, keypad[digit][i] + res, index - 1);``    ``}``}` `// Driver Code``int` `main()``{``    ``// Given mobile keypad``    ``vector<``char``> keypad[] =``    ``{``        ``{}, {},        ``// 0 and 1 digit don't have any characters associated``        ``{ ``'a'``, ``'b'``, ``'c'` `},``        ``{ ``'d'``, ``'e'``, ``'f'` `},``        ``{ ``'g'``, ``'h'``, ``'i'` `},``        ``{ ``'j'``, ``'k'``, ``'l'` `},``        ``{ ``'m'``, ``'n'``, ``'o'` `},``        ``{ ``'p'``, ``'q'``, ``'r'``, ``'s'``},``        ``{ ``'t'``, ``'u'``, ``'v'` `},``        ``{ ``'w'``, ``'x'``, ``'y'``, ``'z'``}``    ``};` `    ``// Given input array``    ``int` `input[] = { 2, 3, 4 };``  ` `    ``// Size of the array``    ``int` `n = ``sizeof``(input)/``sizeof``(input);` `    ``// Function call to find all combinations``    ``findCombinations(keypad, input, string(``""``), n - 1);` `    ``return` `0;``}`

## C

 `#include ``#include ` `// hashTable[i] stores all characters that correspond to``// digit i in phone``const` `char` `hashTable``    ``= { ``""``,    ``""``,    ``"abc"``,  ``"def"``, ``"ghi"``,``        ``"jkl"``, ``"mno"``, ``"pqrs"``, ``"tuv"``, ``"wxyz"` `};` `// A recursive function to print all possible words that can``// be obtained by input number[] of size n.  The output``// words are one by one stored in output[]``void` `printWordsUtil(``int` `number[], ``int` `curr_digit,``                    ``char` `output[], ``int` `n)``{``    ``// Base case, if current output word is prepared``    ``int` `i;``    ``if` `(curr_digit == n) {``        ``printf``(``"%s "``, output);``        ``return``;``    ``}` `    ``// Try all 3 possible characters for current digir in``    ``// number[] and recur for remaining digits``    ``for` `(i = 0; i < ``strlen``(hashTable[number[curr_digit]]);``         ``i++) {``        ``output[curr_digit]``            ``= hashTable[number[curr_digit]][i];``        ``printWordsUtil(number, curr_digit + 1, output, n);``        ``if` `(number[curr_digit] == 0``            ``|| number[curr_digit] == 1)``            ``return``;``    ``}``}` `// A wrapper over printWordsUtil().  It creates an output``// array and calls printWordsUtil()``void` `printWords(``int` `number[], ``int` `n)``{``    ``char` `result[n + 1];``    ``result[n] = ``'\0'``;``    ``printWordsUtil(number, 0, result, n);``}` `// Driver program``int` `main(``void``)``{``    ``int` `number[] = { 2, 3, 4 };``    ``int` `n = ``sizeof``(number) / ``sizeof``(number);``    ``printWords(number, n);``    ``return` `0;``}`

## Java

 `// Java program to implement the``// above approach``import` `java.util.*;``import` `java.lang.*;``import` `java.io.*;``class` `NumberPadString{``     ` `static` `Character[][] numberToCharMap;` `private` `static` `List printWords(``int``[] numbers,``                                       ``int` `len,``                                       ``int` `numIndex,``                                       ``String s)``{``  ``if``(len == numIndex)``  ``{``    ``return` `new` `ArrayList<>(Collections.singleton(s));``  ``}``  ` `  ``List stringList = ``new` `ArrayList<>();``  ` `  ``for``(``int` `i = ``0``;``          ``i < numberToCharMap[numbers[numIndex]].length; i++)``  ``{``    ``String sCopy =``           ``String.copyValueOf(s.toCharArray());``    ``sCopy = sCopy.concat(``            ``numberToCharMap[numbers[numIndex]][i].toString());``    ``stringList.addAll(printWords(numbers, len,``                                 ``numIndex + ``1``,``                                 ``sCopy));``  ``}``  ``return` `stringList;``}``    ` `private` `static` `void` `printWords(``int``[] numbers)``{``  ``generateNumberToCharMap();``  ``List stringList =``       ``printWords(numbers, numbers.length, ``0``, ``""``);``  ``stringList.stream().forEach(System.out :: println);``}` `private` `static` `void` `generateNumberToCharMap()``{``  ``numberToCharMap = ``new` `Character[``10``][``5``];``  ``numberToCharMap[``0``] = ``new` `Character[]{``'\0'``};``  ``numberToCharMap[``1``] = ``new` `Character[]{``'\0'``};``  ``numberToCharMap[``2``] = ``new` `Character[]{``'a'``,``'b'``,``'c'``};``  ``numberToCharMap[``3``] = ``new` `Character[]{``'d'``,``'e'``,``'f'``};``  ``numberToCharMap[``4``] = ``new` `Character[]{``'g'``,``'h'``,``'i'``};``  ``numberToCharMap[``5``] = ``new` `Character[]{``'j'``,``'k'``,``'l'``};``  ``numberToCharMap[``6``] = ``new` `Character[]{``'m'``,``'n'``,``'o'``};``  ``numberToCharMap[``7``] = ``new` `Character[]{``'p'``,``'q'``,``'r'``,``'s'``};``  ``numberToCharMap[``8``] = ``new` `Character[]{``'t'``,``'u'``,``'v'``};``  ``numberToCharMap[``9``] = ``new` `Character[]{``'w'``,``'x'``,``'y'``,``'z'``};``}` `// Driver code ``public` `static` `void` `main(String[] args)``{``  ``int` `number[] = {``2``, ``3``, ``4``};``  ``printWords(number);``}``}` `// This code is contributed by ankit pachori 1`

## Python3

 `# hashTable[i] stores all characters``# that correspond to digit i in phone``hashTable ``=` `["``", "``", "``abc``", "``def``", "``ghi``", "``jkl",``             ``"mno"``, ``"pqrs"``, ``"tuv"``, ``"wxyz"``]` `# A recursive function to print all``# possible words that can be obtained``# by input number[] of size n. The``# output words are one by one stored``# in output[]`  `def` `printWordsUtil(number, curr, output, n):``    ``if``(curr ``=``=` `n):``        ``print``(output)``        ``return` `    ``# Try all 3 possible characters``    ``# for current digir in number[]``    ``# and recur for remaining digits``    ``for` `i ``in` `range``(``len``(hashTable[number[curr]])):``        ``output.append(hashTable[number[curr]][i])``        ``printWordsUtil(number, curr ``+` `1``, output, n)``        ``output.pop()``        ``if``(number[curr] ``=``=` `0` `or` `number[curr] ``=``=` `1``):``            ``return` `# A wrapper over printWordsUtil().``# It creates an output array and``# calls printWordsUtil()`  `def` `printWords(number, n):``    ``printWordsUtil(number, ``0``, [], n)`  `# Driver function``if` `__name__ ``=``=` `'__main__'``:``    ``number ``=` `[``2``, ``3``, ``4``]``    ``n ``=` `len``(number)``    ``printWords(number, n)` `# This code is contributed by prajmsidc`

## Javascript

 ``

Output:

```adg adh adi aeg aeh aei afg afh afi bdg
bdh bdi beg beh bei bfg bfh bfi cdg cdh
cdi ceg ceh cei cfg cfh cfi
Process returned 0 (0x0)   execution time : 0.025 s
Press any key to continue.```

Complexity Analysis:

• Time Complexity: O(4n), where n is a number of digits in the input number.
Each digit of a number has 3 or 4 alphabets, so it can be said that each digit has 4 alphabets as options. If there are n digits then there are 4 options for the first digit and for each alphabet of the first digit there are 4 options in the second digit, i.e for every recursion 4 more recursions are called (if it does not match the base case). So the time complexity is O(4n).
• Space Complexity:O(1).
As no extra space is needed.

Reference:
Buy Programming Interviews Exposed: Secrets to Landing Your Next Job 3rd Edition from Flipkart.com