Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
203 views9 pages

Puzzle Interview Questions

The document describes how to implement a MaxStack class with a getMax() method that returns the largest item in the stack in constant time. It does this by maintaining two stacks - one for the regular stack contents and one called maxesStack to track the maximum values. Whenever an item is pushed or popped, the corresponding action is also performed on maxesStack if the item is equal to the current max.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
203 views9 pages

Puzzle Interview Questions

The document describes how to implement a MaxStack class with a getMax() method that returns the largest item in the stack in constant time. It does this by maintaining two stacks - one for the regular stack contents and one called maxesStack to track the maximum values. Whenever an item is pushed or popped, the corresponding action is also performed on maxesStack if the item is equal to the current max.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Building a Stack with a getMax() function

Suppose you had a Stack class. Write a new class MaxStack which, in addition to push() and pop(),
has a method getMax() which returns the largest item in the stack. Use your existing Stack class to
store the stacks contents.
Dont just use pop() to dig through your stack to find the maxdo something that lets you return
the max in constant time.
Solution
We could have an instance variable where we hold the max, but theres a problemwhen we pop
that item from our stack its no longer the max. Now we have to dig through our stack to find the
new max. Ideally wed keep track of the current max as well as what the new max will be when that
max is popped.
The trick is to have two instances of Stack inside our MaxStack. One holds the actual stack
contents, while the other (call it maxesStack) holds the maxes. Whenever we push() an item, if its
larger than the top item in maxesStack, we also push it to maxesStack. Whenever we pop() an item,
if its the same as the top item in maxesStack(), we also pop() it from maxesStack.
So at any given point we can get the overall max in constant time be peeking at the top item in
maxesStack.

Getting a fair result with an unfair coin


How can you get a fair coin toss if someone hands you a coin that is weighted to come up heads
more often than tails?
We are NY Tech asks: How many unique areas of human knowledge have the right size of
passionate users to make it as a Stack Exchange site? Answer: 30,000.

Storing 1 million phone numbers


What is the most efficient way, memory-wise, to store 1 million phone numbers? Apparently this is
an interview question at Google, although this seems like its a bit too easy.

Reverse a String
Reverse a String
A typical programming interview question is reverse a string, in place. if you understand pointers,
the solution is simple. even if you dont, it can be accomplished using array indices. i usually ask
candidates this question first, so they get the algorithm in their head. then i play dirty by asking them

to reverse the string word by word, in place. for example if our string is the house is blue, the return
value would be blue is house the. the words are reversed, but the letters are still in order (within the
word).

Solution
Solving the initial problem of just reversing a string can either be a huge help or a frustrating
hinderance. most likely the first attempt will be to solve it the same way, by swapping letters at the
front of the string with letters at the back, and then adding some logic to keep the words in order. this
attempt will lead to confusion pretty quickly.
for example, if we start by figuring out that the is 3 letters long and then try to put the t from the
where the l from blue is, we encounter a problem. where do we put the l from blue? hmm
well we could have also figured out how long blue was and that would tell us where to put the l
at but the e from blue needs to go into the space after the. argh. its getting quite confusing. in
fact, i would be delighted to even see a solution to this problem using this attack method. i dont
think its impossible, but i think it is so complex that its not worth pursuing.
heres a hint. remember before when we just reversed the house is blue? what happened?
initial: the house is blue
reverse: eulb si esuoh eht
look at the result for a minute. notice anything? if you still dont see it, try this.
initial: the house is blue
reverse: eulb si esuoh eht
wanted : blue is house the
the solution can be attained by first reversing the string normally, and then just reversing each word.

100 Doors in a Row


100 Doors in a Row
Problem: you have 100 doors in a row that are all initially closed. you make 100 passes by the doors
starting with the first door every time. the first time through you visit every door and toggle the door
(if the door is closed, you open it, if its open, you close it). the second time you only visit every 2nd
door (door #2, #4, #6). the third time, every 3rd door (door #3, #6, #9), etc, until you only visit the
100th door.

question: what state are the doors in after the last pass? which are open which are closed?

Solution
For example, after the first pass every door is open. on the second pass you only visit the even
doors (2,4,6,8) so now the even doors are closed and the odd ones are opened. the third time
through you will close door 3 (opened from the first pass), open door 6 (closed from the second
pass), etc..
question: what state are the doors in after the last pass? which are open which are closed?
solution: you can figure out that for any given door, say door #42, you will visit it for every divisor it
has. so 42 has 1 & 42, 2 & 21, 3 & 14, 6 & 7. so on pass 1 i will open the door, pass 2 i will close it,
pass 3 open, pass 6 close, pass 7 open, pass 14 close, pass 21 open, pass 42 close. for every pair
of divisors the door will just end up back in its initial state. so you might think that every door will end
up closed? well what about door #9. 9 has the divisors 1 & 9, 3 & 3. but 3 is repeated because 9 is a
perfect square, so you will only visit door #9, on pass 1, 3, and 9 leaving it open at the end. only
perfect square doors will be open at the end.

Red Marbles, Blue Marbles


Red Marbles, Blue Marbles

Problem: you have two jars, 50 red marbles, 50 blue marbles. you need to place all the marbles into
the jars such that when you blindly pick one marble out of one jar, you maximize the chances that it
will be red. (when picking, youll first randomly pick a jar, and then randomly pick a marble out of that
jar) you can arrange the marbles however you like, but each marble must be in a jar.

Solution
Chance! chance is easy if you know how to do the formula. we know that we have two choices to
make. first well pick a jar, and each jar will have a 1/2 chance of being picked. then well pick a
marble, and depending how we stack the marbles, well have a (# of red marbles in jar)/(# of total
marbles in jar) chance of getting a red one.
for example, say we put all the red marbles into jar A and all the blue ones into jar B. then our
chances for picking a red one are:

1/2 chance we pick jar A * 50/50 chance we pick a red marble


1/2 chance we pick jar B * 0/50 chance we pick a red marble
do the math and you get 1/2 chance for a red marble fromjar A and a 0/2 chance for a red marble
from jar B. add em up and you get the result = 1/2 chance for picking a red marble.
think about it for awhile and see if you can figure out the right combination. we had a 50/50
(guaranteed) chance in picking a red marble from jar A, but we didnt have to have 50 red marbles in
there to guarantee those fantastic odds, did we? we couldve just left 1 red marble in there and the
odds are still 1/1. then we can take all those other marbles and throw them in jar B to help the odds
out there.
lets look at those chances:
1/2 we pick jar A * 1/1 we pick a red marble
1/2 we pick jar B * 49/99 we pick a red marble
do the math and add them up to get 1/2 + 49/198 = 148/198, which is almost 3/4.
we can prove these are the best odds in a somewhat non-formal way as follows. our goal is to
maximize the odds of picking a red marble. therefore we can subdivide this goal into maximizing the
odds of picking a red marble in jar A and maximizing the odds of picking a red marble in jar B. if we
do that, then we will have achieved our goal. it is true that by placing more red marbles into a jar we
will increase the chances of picking a red marble. it is also true that by reducing the number of blue
marbles in a jar we will increase the odds also. weve maximized the odds in jar A since 1/1 is the
maximum odds by reducing the number of blue marbles to 0 (the minimum). weve also maximized
the number of red marbles in jar B. if we added any more red marbles to jar B we would have to
take them out of jar Awhich reduce the odds there to 0 (very bad). if we took any more blue ones out
of jar B we would have to put them injar A which reduce the odds there by 50% (very bad).
it wasnt really a good proof, but QED anyway

Bumblebee
problem: two trains enter a tunnel 200 miles long (yeah, its a big tunnel) travelling at 100 mph at the
same time from opposite directions. as soon as they enter the tunnel a supersonic bee flying at 1000
mph starts from one train and heads toward the other one. as soon as it reaches the other one it
turns around and heads back toward the first, going back and forth between the trains until the trains
collide in a fiery explosion in the middle of the tunnel (the bee survives). how far did the bee travel?

Solution
solution: this puzzle falls pretty high on my aha scale. my first inclination when i heard it was to think
ok, so i just need to sum up the distances that the bee travels but then you quickly realize that its
a difficult (not impossible) summation which the interviewer could hardly expect you to answer
(unless i guess if you are looking for a job as a quant). there must be a trick you say. eh, sort of i
guess, enough to say that this question is a stupid interview question.
the tunnel is 200 miles long. the trains meet in the middle travelling at 100 mph, so it takes them an
hour to reach the middle. the bee is travelling 1000 mph for an hour (since its flying the whole time
the trains are racing toward one another) so basically the bee goes 1000 miles.
there is no process to explain, so this question cant possibly teach you anything about the person.
they either know it or they dont and if they already knew it before you asked, youre not going to be
able to tell when they give you the answer. so dont ask this question. and if someone asks you this
question, just tell them youve already heard it before.

int atoi( char* pStr )


int atoi( char* pStr )
Problem: write the definition for this function without using any built-in functions. if pStr is null, return
0. if pStr contains non-numeric characters, either return 0 (ok) or return the number derived so far
(better) (e.g. if its 123A, then return 123). assume all numbers are positive. plus or minus signs can
be considered non-numeric characters. in order to solve this program, the programmer must
understand the difference between the integer 0 and the character 0, and how converting 0 to an
int, will not result in 0. in other words, they have to understand what ascii is all about.

Solution
string manipulation functions are great programming questions. they test whether the user can
understand and translate into code simple algorithms. string functions test pointer arithmetic which
usually shows a knowledgeable programmer. also there are usually multiple solutions, some more
efficient than others. plus people use them all the time so they should understand how they work. my
favorite is atoi and i start the problem like this:
int atoi( char* pStr )

write the definition for this function without using any built-in functions. if pStr is null, return 0. if pStr
contains non-numeric characters, either return 0 (ok) or return the number derived so far (better)
(e.g. if its 123A, then return 123). assume all numbers are positive. plus or minus signs can be
considered non-numeric characters. in order to solve this program, the programmer must
understand the difference between the integer 0 and the character 0, and how converting 0 to an
int, will not result in 0. in other words, they have to understand what ascii is all about. if they are
stuck solving this problem, just ask them first to write:
charToInt(char c)
if they cant do that then they basically missed half the problem. any moderately talented
programmer who has a CS degree knows how to convert a char to an int. (note i said convert, not
cast. charToInt('9') should return 9.)
when they start to solve the problem you will notice that they must make a choice in how they will
process the string from left to right or right to left. i will discuss both methods and the difficulties
encountered in each.
right to left this method starts at the right hand letter of the string and converts that character to
an int. it then stores this value after promoting it to its correct tens place.
int atoi( char* pStr )
{
int iRetVal = 0;
int iTens = 1;
if ( pStr )
{
char* pCur = pStr;
while (*pCur)
pCur++;
pCur--;
while ( pCur >= pStr && *pCur <= '9' && *pCur >= '0' )
{
iRetVal += ((*pCur - '0') * iTens);
pCur--;
iTens *= 10;
}

}
return iRetVal;

left to right this method keeps adding the number and multiplying the result by ten before
continuing to the next number. e.g. if you had 6234 and you processed from left to right youd have
6, then if you kept reading youd multiply your result by 10 (6*10) to add a zero for where the next

number would go. 60, and then youd slide the 2 into the zero place you just made. 62. do it again,
620, slide the next number in, 623.
int atoi( char* pStr )
{
int iRetVal = 0;

if ( pStr )
{
while ( *pStr && *pStr <= '9' && *pStr >= '0' )
{
iRetVal = (iRetVal * 10) + (*pStr - '0');
pStr++;
}
}
return iRetVal;

i think the left to right method is a little bit cleaner, or maybe its just cooler. but both are correct.
remember that debugging code on paper is somewhat hard. most programmers arent used to
studying code that much when you can just hit F-7, compile and see if the compiler barfs or not. if
you notice an error, just ask them to step through a sample string drawing out what is happening
with all the variables and the pointers in every step. they should find their mistake then and fix it (no
points deducted)

Daughters Ages
Daughters Ages

Two MIT math grads bump into each other at Fairway on the upper west side. They havent seen
each other in over 20 years.
the first grad says to the second: how have you been?
second: great! i got married and i have three daughters now
first: really? how old are they?
second: well, the product of their ages is 72, and the sum of their ages is the same as the number
on that building over there..
first: right, ok.. oh wait.. hmm, i still dont know
second: oh sorry, the oldest one just started to play the piano
first: wonderful! my oldest is the same age!
problem: how old are the daughters?

Solution
solution: start with what you know. you know there are 3 daughters whose ages multiply to 72. lets
look at the possibilities
Ages:
1 1 72
1 2 36
1 3 24
1 4 18
1 6 12
1 8 9
2 2 18
2 3 12
2 4 9
2 6 6
3 3 8
3 4 6

Sum of ages:
74
39
28
23
19
18
22
17
15
14
14
13

after looking at the building number the man still cant figure out what their ages are (were assuming
since hes an MIT math grad, he can factor 72 and add up the sums), so the building number must
be 14, since that is the only sum that has more than one possibility.
finally the man discovers that there is an oldest daughter. that rules out the 2 6 6 possibility since
the two oldest would be twins. therefore, the daughters ages must be 3 3 8.
(caveat: an astute reader pointed out that it is possible for two siblings to have the same age but not be twins, for instance one is born
in january, and the next is conceived right away and delivered in october. next october both siblings will be one year old. if a candidate
points this out, extra credit points to him/her.)

this question is pretty neat, although there is certainly a bit of an

aha factor to it. the clues are given

in such a way that you think you are missing information (the building number), but whats important
isnt the building number, but the fact that the first man thought that it was enough information, but
actually wasnt.
even if the candidate doesnt know the solution, they could come up with some interesting thoughts.
if they just stare at you and shrug i dunno then thank them for their time and dont give them
a fogcreek pen.

GO TO THIS LINK CLIK HERE FOR MORE


PUZZLES.VERY IMPORTANT.EVERY
INTERVIEW ENDS WITH A PUZZLE QUESTION
http://www.techinterview.org/page/2/

You might also like