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



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 ??




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. 🙂


Print All Combinations of an array

Today I will discuss how to get all the combinations of array elements.
First what do you mean by Combinations ?

In mathematics, a combination is a way of selecting members from a grouping, such that (unlike permutations) the order of selection does not matter.

Let’s see an example : suppose your array contains following three elements :
1,2,3. Then the list of combinations is :

for array length we have 2^3 combinations. Combinations is nothing but a power set. For a set of length n, a power set is of length 2^n. So for a given array of length n, we can have 2^n total combinations, out of which one is empty set.

There are two ways to do this one is recursive approach or iterative approach. We will do recursive approach today.Here is the code for getting all the combinations of array elements.