0

Print all possible words from phone number digits

Classic interview question :

Print all possible words from phone number digits.

This question is asked by companies like microsoft, google, facebook. Lets see example input/output to understand this problem.

This is the cellphone keypad

 

wp_ss_20141009_0001

Where pressing ‘2’ you can type letters -> ‘a’,’b’,’c’

using 3 -> ‘d’,’e’,’f’ etc.

So given the number 23 what are the possible words ??

ad,ae,af

bd,be,bf

ce,ce,cf

To make it clear in your head you can imagine, what happens when you press 2,3 keys while typing a text, if you press 2 first and then 3 what different words can you type ?  (Answer is list of words written above) since you pressed two keys all the words will be of length 2.

Lets write a function that given the key as input returns list of characters it represents, so for instance if key is ‘2’ function returns a char[] {‘a’,’b’,’c’}.

Now lets write a recursive function that will use the above function to print all possible words.

I am using a variable depth, to stop the recursion. And using Console.Writeline() to print the strings.

Interesting application of this problem can be, to convert given phone number to a readable word.

for example : 27753 -> APPLE.

Leave a comment if you like the post. 🙂


Warning: count(): Parameter must be an array or an object that implements Countable in /home/algotu5/public_html/wp-includes/class-wp-comment-query.php on line 405