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

0

Program to count number of comments in code

This is an interesting problem, and a good interview question.

Count the number of comments in Code file

Lets define the comments :

1) Single line comments start with //

2) Multi line comments start with /* and end with */

What are the different possible comments in the code ?

// at the start of the line,

some code here and then // some code

“C://somepath” this is not a comment !! (Our code should be able to ignore this)

‘//’ Even this is not a comment we should ignore (//) here.

/* some line */

/* /**/*/

/*

//

//

*/

These are  some of the possible combinations that form comments in source code.

Now we can solve this using traditional approach of checking first character and second character and deciding based on that, but i dont like it,

it will involve lot of if’s and hard to keep track of all the conditions. Also the code will not be readable.

How about creating a state machine like the following :

WP_20140918_21_30_17_Pro

So we start with initial state “Normal Content” if we get a / there then we go to state -> Single Line Comment start , here if we get another /

we go to  state -> single line comment end. Similarly for the rest conditions.

And here is the code for above state machine :

Leave a comment if you like the post 🙂

 

1

Fizz Buzz Problem

Fizz Buzz problem is a famous interview question, Lets discuss this problem.

Problem Statement :

For 1-100 numbers :

if the number is divisible by 5 print – “Buzz”

if the number is divisible by 3 print – “Fizz”

if the number is divisible by both print – “Fizz Buzz”

I have a created a video tutorial :

Here is the code shown in the video :