# Software Engineering Interview Questions

Software engineering interview questions shared by candidates

## Top Interview Questions

### Java Software Engineer at SAP was asked...

1.Java Basics. 2.Plethora of Multithreading questions.GC 3.Simple data structure. (BFS) variation 4.Database Basics 1 AnswerI fumbled in 1 questions which was the nail in the coffin. |

Explain the development process of a previous project. 1 AnswerI began with wireframing and worked forward through the mysql database, java backend, and the javascript and html front end. (I had a whiteboard to draw out my process) |

### Payroll Manager at Quality Systems was asked...

Have you ever had to terminate anyone and how did you handle it? 1 AnswerI spoke to the employee a few times and documented the conversations. I put the person on a performance plan. However, in the end the actual termination was handled by HR with me sitting in on the process. |

Suppose you had eight identical balls. One of them is slightly heavier and you are given a balance scale . What's the fewest number of times you have to use the scale to find the heavier ball? 45 Answers3 times. (2^3 = 8) Two. Split into three groups of three, three, and two. weigh the two groups of three against each other. If equal, weigh the group of two to find the heavier. If one group of three is heavier pick two of the three and compare them to find the heaviest. Brian - this would be correct if you in fact were using a weighing scale, and not a balance scale. The ability to weigh one group against another with a balance scale allows Marty's answer to be a correct answer. Although - the question as worded provides a loophole. If it had been worded as "What's the fewest number of times you have to use the scale to CONSISTENTLY find the heavier ball", then Marty's answer would be the only correct answer. However, it is possible that you could get lucky and find the heavier ball in the first comparison. Therefore, the answer to the question as stated, is ONE. Show More Responses This question is from the book "How to move Mt Fuji".... Marty has already got the right answer. Actually Bill, by your interpretation of the question the answer is zero, because you could just pick a ball at random. If you get lucky, then you've found the heaviest ball without using the scale at all, thus the least possible amount of times using the scale would be zero. The answer is 2, as @Marty mentioned. cuz its the worst case scenario which u have to consider, otherwise as @woctaog mentioned it can be zero, u just got lucky picking the first ball.... None- weigh them in your hands. Assuming that the balls cannot be discerned by physical touch, the answer is 3. You first divide the balls in two groups of 4, weigh, and discard the lighter pile. You do the same with the 4 remaining, dividing into two groups of 2, weighing, and discarding the lighter pile. Then you weigh the two remaining balls, and the heavier one is evident. 2 3a+3b+2 = 8 if wt(3a)==wt(3b) then compare the remaining 2 to find the heaviest if wt(3a) !== wt(3b) then ignore group of 2 discard lighter group of 3 divide the remaining group of 3 into 2+1 weigh those 2 If == the remaing 1 is the heaviest if !== the heaviest will be on the scale With the systematic approach, the answer is 3. But, if you randomly choose 2 balls and weigh them, and by coincidence one of these two is the heavier ball, then the fewest number of times you'd have to use the scale is 1. Although the real question is: are the balls truly identical if one is heavier than the rest? just once. Say you are lucky and pick the heavy ball. One use of the scale will reveal your lucky choice so once, or the creative answer zero if you allow for weighing by hand Without judging by hand: Put 4 balls on one side, and 4 on the other. Take the heavier group and divide again, put 2 balls on one side, and 2 on the other. Take the 2 that were heavier, and put one on each side. You've now found the heaviest ball. This is using the scale 3 times, and will always find the right ball. Show More Responses None. They are identical. None is heavier. 2 weighings to find the slightly heavier ball. Step 1. compare 2 groups of three balls. Case 1. if they are both equal in weight, compare the last 2 balls - one will be heavier. case 2. If either group of 3 balls is heavier, take 2 balls from the heavier side. compare 1 ball against the 2nd from the heavy group result 1. if one ball is heavier than the other, you have found the slightly heavier ball. result 2. if both balls are equal weight, the 3rd ball is the slightly heavier ball. Easy Shmeezi Fewest - get lucky and pick the heaviest one. But wait! How would you know it is the heaviest one by just weighing one ball? Your logic is flawed. Two groups of four. Split heavier one, weigh. Split heavier one, weigh. 3 times. i think its 3. i would take it like this OOOO OOOO then OO OO then OO problem solved. i do this everyday. bye. praise be to allah. thats it. It's 2. Period. If you can't figure it out look it up online or in "How Would You Move Mount Fuji" (like somebody else said). This is one of the most basic brainteasers you could be asked in an interview. The answer is 2. 1) Divide the balls into 3 groups. 2 piles with 3 balls each, 1 pile with 2 balls. 2) Weigh the 2 piles of 3 balls. If both piles are the same weight, discard all 6 and weigh the last 2 to find the heavier one. 3) If 1 pile of 3 is heavier than the other, discard the lighter pile and the pile of 2 balls. Weigh 2 of the remaining 3 balls from the heavier pile. If both of the weighed balls are equal, the last ball is the heavier one. 2=if all the balls are identical and you pick up the first...weigh it and the second one is lighter or heavier then you've found the heavier ball in the least amount of attempts. 1=if all the balls are identical and you pick up the first...balance it and the second one is lighter or heavier then you've found the heavier ball in the least amount of attempts. Amy is 100% correct for the following reason: everyone (except Amy) is solving the theoretical problem. The practical side of the problem - notwithstanding jimwilliams57's brilliant observation that if one weighs more than the others IT IS NOT IDENTICAL (would have loved to see the interviewer's face on that one) - in order to 'weigh' them on a scale, one has to pick them up, therefore, you will immediately detect the heavier one without weighing: pick-up three and three ... no difference, no need to weight. Pick-up the remaining two to determine the heavier one. Steve First off, take yourself through the process visually and forget square roots, that doesnt apply here and here is why: The question is the Minimum, not the MAXIMUM. BTW, the max would be 7 ( 8-1); you are comparing 2 objects, so 1 ball is eliminated automatically in the first step. Anyway, you have a fulcrom of which you are placing 2 of 8 objects on each end. If by chance you pick the slightly heavier object as one of the two balls, you have in fact, found the slightly heavier one in the first round... btw dont be a smartass with your interviewer, he is looking for smarts not smarmy;) Show More Responses Respectfully, the folks who are answering "3" are mathematically modeling the nature of the balance incorrectly. Performing a measurement on a balance scale is not binary. It is trinary. Each measurement gives you one of three responses: The left is heavier, the right is heavier, or they are equal. So while you do need three binary bits to specify a number from one to eight, you need only two TRINARY-DIGITS Formally, you want the smallest value of n such that 3^n >= 8. The answer is 2. Note that you could add a ninth ball, and still, you'd only need to make two measurements. Of course, the smarty pants answer would be one. Just pick two balls at random and be lucky to have chosen the heavy one. But you're not guaranteed to be able to do it in just one measurement. English isn't my mother tongue... What is a balance scale? If looking up on Google, I find some devices with two bowls on a bar bearing in the center. Hence, the answer is once (if I'm luck enough to select the heavier ball in teh first measurement) If a balance scale allows to measure only one ball at a time, then it would take two measurements, unless you'd have more information on the weight, which is not listed here, hence doesn't exist in the context of the question^. 3 times. Not having looked at the other comments, hopefully, I am the 26th to get this right. Put the balls 4 and 4 on the scale, Take the heavier side and place those balls 2 and 2 on the scale. Take the heavier side and place them 1 and 1 giving the heaviest ball. OK, now I read the comments and see that the people, like the question are divided into to groups, systematic approach people that say 3 (like I did) and analytic people that say 2. It takes a systematic person (me) a minute to get the answer. I'm guessing it took the analytic 5 minutes just to interpret all the ramifications of the question, i.e. they aren't idenitical if..., do it by hand..., get lucky. minimum is 1 (if lucky - 25% chance by picking 2 balls at random) & max is 2 (using most efficientl process to absolutely determine without luck - 3/3/2 scenario) While Symantec was busy weighing my balls I took a job with NetApp.... They need to focus on hiring good, capable security engineers, not weighing their balls. The point of these interview questions is to both check your logical brain function and to hear how you think. Most of you are just posting jerk off answers trying to be funny, or you are really dumb. These answer get you nowhere with me in an interview. Think out loud, go down the wrong path back track try another logic path, find the answer. None of this "0 if you use your hands". That is fine if you are interviewing for a job in advertising where creativity is desired, nobody wants you writing code like an 8 year old. You have 12 balls, equally big, equally heavy - except for one, which is a little heavier. How would you identify the heavier ball if you could use a pair of balance scales only twice? The problem is based on Binary Search. Split the balls into groups of 4 each. Choose the heavier group. Continue till you get the heavier ball. This can be done in log(8) (base 2) operations, that is, 3. Since there is only one scale available to weigh. You first divide the balls in half. Weigh each group, take the heaviest group. This is using the scale twice so far. Now, divide the previous heaviest group into half, weigh both groups. Take the heaviest. Divide this last group and take the heaviest. This is the heaviest ball. We have used the scale 5 times. Show More Responses Would it be wrong to say for a sample size as small as 8, we might as well not waste time thinking about an optimal solution and just use the scale 7 times, as this will be more efficient than coming up with an ideal solution prior to using the scale? 3. I stumbled across this while looking for something else on Google but I had to answer. It is 2, split balls into 2,3 and 3. weigh the 2 groups of 3 against each other. If equal weigh the group of 2 and the heaviest is obvious. If they are not equal keep heavy group of 3 and weigh 2 of the balls. if equal heaviest ball is one you didn't weigh. If not equal the heavy ball is obvious. 2 times. 8 balls. 1st step: [3] [3] [2] 2nd step: [[1] [1] [1]] [[1] [1] [1]] [[1] [1]] No idea The fewest number of times to use the scale to find the heavier would be Eight to One times ? It will actually be 1 because the question asks what's the fewest amount of times which is one because you could just get lucky you can use any method you want it would still be one because that is the fewest amount of turns you can have It's one. The fewest number of tries on using a balance scale would be one. If you put one ball on each side and one is heavier, you have the found the heavier ball. Use an equilateral triangular lamina which is of uniform mass throughout. It is balanced on a pole or a similar structure. Steps: Place 2 balls at each corner (total 6 balls) i. if the odd ball is one of those, one side will either go up or go down. Now repeat the process with one ball at each corner including the 2 unbalanced ones. ii. if balance is perfect, repeat the process with the remaining two balls and one of the already weighed balls. test answer 2016-01-12 00:34:07 +0000 Show More Responses You would not be able to find a ball heavier than the others. All eight balls are identical; therefore, they must all be the same weight. Correct answer has already been posted. I just want to contribute some theoretical analysis. Given N balls, one of them is heavier. Finding out the ball requires log3(N) trit of information. (trit is the 3-base version of bit). Each weighing may give you one of the three outcomes: equal, left-heavier, right-heavier. So the amount of information given by each weighing is upper-bounded at 1 trit. Therefore, theoretical lower-bound for number of weighings in the worst case is log3(N), which is actually attainable. So 27 such balls need only 3 weighings and 243 balls need only 5 weighings, etc. |

### Software Engineer at Raytheon was asked...

In front of you are three light switches. Only one does anything, and it turns on the light downstairs. From here you can't see the light, and it makes no sound. You must determine which switch operates the light, BUT you can only go check it once. How do you figure out which switch is for the light? 26 AnswersFlip any switch you want. Wait for about 5-10 minutes to let the bulb heat up. Flip that same switch off, and another one on. Go check the light. If it's off and hot, it was the first switch, if it's on it was the second and if it's cold and off, it was the last one. flip one switch look down stairs with out going down stairs and look if there is any light. Continue this until you see the light. Flip switches, keep checking, at the foor of the stairs, until you see light; that will be the switch! Show More Responses flip them all on. only one does anything so the other two really doesn't mean anything. Open the switch plate, using an electrical tester- test for the live wire. Only one will test positive. On a multiple unit switch the farthest left is often the first to be hooked up, Flip the switch on one end, wait a "long" time (e.g., 15 minutes); then flip the middle switch; them immediately go check the light for on/off status and temperature. If off: the switch you didn't change controls the light; If on and surrounding fixtures slightly warm, the middle switch controls the light; If on and surrounding fixtures fully warm of hot, the first switch controls the light. The first answer is right of course. Most of the other answers would make the interviewer realize you don't listen, don't understand the question, or don't care. Either way, not what you want in an interview. Don't jerk around. I frankly enjoy all the wry responses! Because this is just one of many ridiculously shallow and pointless interview questions that reveals much more about the intent and competence of the interviewer rather than the interviewee. Preparing for and sitting through an interview is tense enough - so it is totally deflating when a "gotcha" question like this is thrown at you. When I hear a question like this during an interview, I immediately know that the interviewer is 1) incredibly lazy and 2) clueless about how to actually gather worthwhile information in order to make an informed decision. Is that person someone you would want working with/supervising you??? Use solution one. Then use the light to get out - unless downstairs is the switch to fire the HR Department. I do like the use "an electrical tester" answer - unless you're interviewing for a safety job. Use solution one. Then use the light to get out - unless downstairs is the switch to fire the HR Department. I do like the use "an electrical tester" answer - unless you're interviewing for a safety job. Collins has the answer - Flip all 3 switches send your helper downstairs to let you know when the light turns on and off. Show More Responses LOL...good luck tripping and stumbling while looking for the warm light bulb in the dark! Turn all three switches on. The flip one switch off at a time and check to see if the light goes off after flipping that switch off. When the light goes off...that was the switch. oops! can only check it once. I dont get the job because I cant follow directions...If i'm in charge of the project, I can check it as many times as I like!!! Take the faceplate off and look inside to see which switch has wires hooked to it. That would be the winner. Tell the HR interviewer to go stick his/her finger in the light socket and scream when you flip the correct switch. It does not have sense because I am not an electrician. So I can flip any switch, after few minutes flip once again this switch and any other and go check to bulb. If it will be dark I can not check anything because I can not find the bulb I it will be light it does not mater which switch operate. I can go forward, :) I'll take the job. I can think of several solutions. I like these questions. And they are not pointless. How you answer such a question, or how you attempt to do it shows ho imaginative you are and whether you persist. A few possible solutions: 1. If it is dark outside, or the building does not have windows, operate the switches one at a time until you hear angry voices from downstairs - nobody likes to stay in the dark. 2. Otherwise, operate the switches one at a time and ask the people downstairs. 3. Do not operate any switch. Take your light-detecting sensor downstairs. The sensor transmits a wireless signal to the receiver in your pocket. Get back to the panel and start flipping the switches until you get the signal from the receiver. 4. Take your bow and three arrows with dull heads (you do not want to damage the switches). Go to a place from where you can see both downstairs and the panel. Start flipping the switches one by one by shooting arrows at them. 5. You need a big fly - one of those you can hear flying. Turn off all the lights in the building. The lights must be on only at the place where you stand and downstairs. Have someone release the fly downstairs - you can hear it buzz. Start flipping the switches one a time and wait. You know you got the right switch when you stop hearing the fly (or when it comes to you). Ask someone to go downstairs and yell up to you when it works. What are you people mentally challenged? You have no way of knowing which switch controls the light. The "correct" answers above assume the light is initially off. If the light started out as on and you performed this test you would get misleading results. I would either ask someone on the team who already knows which light switch it is or I would search the Internet for the solution to figuring it out on my own. I like the answer about requesting someone to go downstairs and check the light while you flip the switch, it shows 3 things about you: #1-You're not afraid to ask for help when needed. #2- It shows you can delegate. These responses coincide with TEAMWORK. Unless the interviewer has specifics, in which you ask. That could be the #3rd answer-BEING RESOURCEFUL by asking questions. It shows your interest in the job and you don't have to be an electrician to figure it out. Show More Responses subduejoy clearly has the answer, it's what I do for most of my problems. The "temperature" method is clever but that assumes the lights are incandescent and you're close enough to the bulbs that you can get there before they cool down to room temperature. An interviewer might look at that answer as clever but wrong because you make assumptions that weren't explicitly allowed (Microsoft would probably say this). My answer would either be. a) Ask for help (shows you not afraid to be a team player b) Do it the electrical engineering way and put a video camera in the room and wait 15 minutes before flipping each switch. It's really a stupid question though that says nothing about how good of an employee you'll be. 1. Flip one switch 2. wait 2 minutes 3. Flip switch off again 4. Flip another switch on 5. Immediately go downstairs and check if a light is on If the light is off, the switch you flipped in step 4 is not correct. 6. Touch the bulb If the bulb is cold, the switch you flipped in step 1 is incorrect. That means that the remaining switch is the correct choice. If the bulb is hot, the switch you flipped in step 1 is the correct choice. |

GIven 9 balls all of which weigh the same except for one, what is the minimum of weighings necessary to find the ball weighs more (or less). 28 AnswersAnswer = Maximum of three steps to find heavy ball. Put one tennis ball aside and put the other 8 on the scale - 4 on each side. If the scale is balanced you're done - the one you put aside is the heavy ball If not Remove the 4 balls on the light side of the scale. The heavy ball is one of the four still on the scale. Spit these four in two on each side of the scale. Remove the two on the light side of the scale. The heavy ball is one of the two remaining balls on the scale. Split the two remaining balls. Your done. Solution #2 - heavier ball found in two steps: Step 1: group 9 balls in sets of 3. Reserve 3 balls(a), put 3 on each side of scale(b) and (c). Observe that heavier ball is in one of three sets, (a), (b) or (c) - either the scale side that dropped or the reserved set, if the scale balanced. Step 2: Split the set with the heavier ball - reserve one and place one on each side of the scale. Observe that heavier ball is one of the 3 balls, - either the scale side that dropped or the reserved ball, if the scale balanced. Solved in two steps. While the solution above is correct, more or less, you first should clarify the question and spell out any assumptions. The assumption here is that you know or are aware beforehand that only one ball is of different weight. Sometimes your ability to clarify and state assumptions is more valuable than getting the right answer. Sometimes you can arrive at the right answer with the wrong logic which helps you solve this problem, but may mess you up in the future. You could do this with two weighings assuming its a two pan balance - (1) place three balls on each side - if they balance out then its the remaining three that has abnormal ball (2) out of that group, place one ball on each side - if balances it out, the abnormal ball is the remaining one. If the weighing in step (1) does not balance out, grab the group of three balls that is light or heavy and repeat step (2) described above. Show More Responses I began with the assumption you could do this with a minimum of three, but I now believe it's four. Perhaps I'm over thinking it though, so I'll explain my "solution". Step 1. Start with three balls on either side of the scale, with a third set waiting on the sidelines. If the scale is balanced, you can move onto the three waiting. 2. place one ball on either side, again with the last one waiting. Should the scales be balanced, it's the last one. 3. If they aren't, take the heavier side off, and place the waiting ball on, if they balance. It's the one you just removed. If they're off canter again, it's whichever side was inconsistent. The hitch with the fourth measurement comes due to the little trip up in the question "To find the ball that weighs more (or less)." If you don't know from the start if you're looking for a heavier or lighter ball, should the scales be off on the first measurement, you'll need to replace three of the balls with the reserves to determine which ones are the odd batch out. The comment about the assumptions is absolutely spot on. For example, I like the answer that says ONE step (weighing) but this assumes a balance scale is used not a device that weighs each ball. Based upon a weighing device that weighs each ball and remembering the question is the MINIMUM number of weighings then the answer is THREE - here is the logic. Each weighing weighs one ball. The minimum number of weighings to identify a difference is two, i.e the first two balls are different in weight. The third weighing will confirm which of the previous two is part of the set of eight balls with the other being the odd one out. Simple....8 of the balls are hollow.....1 is not. Maybe I'm slow but....if I put set A and set B on the scale while reserving set C, and if set A is heavier than set B, how do I know if set C is equal to set A or B without weighing it? Notice the question says "more (or less)". In other words, why wouldn't I have to weigh set C? (This is assuming each set is of 3 balls.) Suncoastgal has a point, and most of the answers above are simplifying this problem a bit. You are not told if the odd ball is heaver or lighter, which complicates things. The most efficient method is that described by 'questions like this...' as method 2. Split balls into 3 groups and weigh two. The worst outcome is if the groups do not weigh the same, so assume that happens. All you know now is that the odd ball is NOT in the reserved group of 3, so set those aside. You don't know which of the two weighed groups contains the odd ball, so now you have 6. Repeat the first step with groups of 2 balls. Again the worst outcome is that the scales don't balance, so you've eliminated 2 more balls and only know that the odd ball is one of 4. As near as I can tell, you still need 2 more steps now to guarantee finding the odd ball: Choose any two balls from the 4 and compare. If they are the same, the odd ball is in the reserved 2, if they differ the odd ball is one of the two you weighed. Now take one of the two balls that might be odd, and weigh against one of the balls you have been setting aside as 'normal'. By the way, although you now know which ball is odd, you may still not know if it's heavier or lighter. If the last weighing balances, you only know that the other ball is odd, and you would have to weigh it against one of the 'normal' balls to see how it is off. You can do this problem in only 2 weighings if you are told whether the odd ball is heavy or light before you begin. Suncoastgal has a point, and most of the answers above are simplifying this problem a bit. You are not told if the odd ball is heaver or lighter, which complicates things. The most efficient method is that described by 'questions like this...' as method 2. Split balls into 3 groups and weigh two. The worst outcome is if the groups do not weigh the same, so assume that happens. All you know now is that the odd ball is NOT in the reserved group of 3, so set those aside. You don't know which of the two weighed groups contains the odd ball, so now you have 6. Repeat the first step with groups of 2 balls. Again the worst outcome is that the scales don't balance, so you've eliminated 2 more balls and only know that the odd ball is one of 4. As near as I can tell, you still need 2 more steps now to guarantee finding the odd ball: Choose any two balls from the 4 and compare. If they are the same, the odd ball is in the reserved 2, if they differ the odd ball is one of the two you weighed. Now take one of the two balls that might be odd, and weigh against one of the balls you have been setting aside as 'normal'. By the way, although you now know which ball is odd, you may still not know if it's heavier or lighter. If the last weighing balances, you only know that the other ball is odd, and you would have to weigh it against one of the 'normal' balls to see how it is off. You can do this problem in only 2 weighings if you are told whether the odd ball is heavy or light before you begin. If the question to identify the odd ball (heavy or light) out of 9 balls is read literally, then the answer is 1 weighing (under the most luckiest of circumstances): weigh 2 sets of 4 balls against each other using a double-pan balance and if you're lucky it will weigh evenly, allowing identification of the not-weighed 9th ball as the odd ball. (The question doesn't say you need to identify whether it was heavy or light.) If the question is what is the least number of weighings it takes to identify the odd ball under the least lucky circumstances then the answer is 4, as best I can come up with. 1. Weigh 2 sets of 3 balls against each other, setting aside the 3rd set of 3 balls. The least lucky result ("LLR") is an imbalance. However, this does identify the 3rd unweighed set as all standard balls. 2. Here's where creative problem solving/out-of-box thinking comes into play. Take a red and black marker and mark one of the heavy balls red and one of the light balls black. Switch the marked balls. LLR --> still an imbalance, though imbalance must remain in the same direction since there is only 1 odd ball (yet to be identified). 3. Repeat step 2 (mark one of the unmarked heavy balls red and one of the unmarked light balls black, switch them and reweigh). LLR --> still an imbalance. 4. Take one of the 3 unweighed balls, previously set aside from the 1st weighing, and substitute it for the last remaining unmarked heavy ball. If this last weighing results in an imbalance then the odd ball is the last remaining light ball (and is light, obviously). If the weighing results in a balance, then the removed unmarked heavy ball was the (heavy) odd ball. These type of interview questions are so lame. They don't sniff out the lazy people, the coders who write crap no one can decipher, and can't or won't write maintainable code. Yes you want people who can problem solve and break down problems into manageable chunks, but how often do software projects fail? Answer = 70-90% and that's mostly due to poor management, not giving clients what they want, feature creep, poor quality, etc. So how is answering this question going to tell me that this new hire has integrity and can throw out his ego and write code for a real life product that people want to use? No wonder so much software is trash. (And yes I've been programming for 25 years and see the same errors happening over and over, it's pathetic and completely fixable.) I read the question as "determine if the odd ball weighs more or less", not "determine which ball is the odd one out". After re-reading the question, it seems like the word "IF" (i.e. "...to find [IF] the ball weighs more (or less)") or the word "THAT" (i.e. "...to find the ball [THAT] weighs more (or less)") is ommitted (purposefully?). I went about answering the my first interpretation and came up with 2 weighings as the MINIMUM required. I assumed we have a scale that can accurately measure the weight in grams (or whatever unit of measurement needed to accurately measure the ball). Step 1. Weigh 8 balls. Divide the total weight by eight. Step 2. Weigh the remaining ball. If you compare the result from each step you'll know if the ball is heavier or lighter than the others. Only 1 step required. Throw all of the balls in a sufficiently deep enough pool of water. The ball that sinks the fastest/slowest is the ball that doesn't weigh the same. If all of the balls float, then it is the ball that is lowest/highest in the water that doesn't weigh the same. Show More Responses The answer should 1 as it asked "the minimum". When you weight 4 balls on each side of the scale and find it equally weight then the 9th ball is definitely the odd ball. You can always got lucky on the first attempt! I understand the Question to be what the minimum of weightings needed is to find out if the different ball weighs more or less than the other 8. The answer is three. 1. You way 1 ball and get its weight 2. Weigh a second and get its weight 3. If they do not weigh the same way a third to see if the different ball is the heavier or lighter one. Or If they weigh the same weigh all the balls and divide by 9 if it is less than one of the balls you weighed the different ball is lighter. If it is more than one of the balls you weighed the different ball is heavier. I agree with Anonymous in that these questions don't tell much about character. However, I can't beleive nobody here is analytical enough to come up with the correct answer. First off, the question is not stated correctly. The scale should be a simple balance, and the objective is to find the "odd" ball AND determine if it is heavy or light. The answer is three. First separate into three groups of three, G1, G2, and G3. In the first two weighings you can determine which group has the "odd" ball AND if the odd ball is heavy or light. Weighing 1 - weigh G1 against G2: Two outcomes 1) G1 == G2 --> Odd ball is in G3, in Weighnig 2, use either G1 or G2 against G3 to determine if Oddball is H or L 2) G1 != G2 -> Odd ball is NOT in G3 but you now know if G1 is heavier or lighter than G2, in Weghing 2, use either G1 or G2 against G3, for instance use G2 and G3, if same, then G1 has oddball and you know if its H or L, if G2 != G3, then G2 has odd ball and you know if it is H or L Now that you know which G it is in And the disposition of the Oddball (Heavy or Light), weigh any two of the Group containing the oddball, and based on your knowledge of wether the oddball is H or L, you know which one it is and its disposition. Any offers?? The question is perfect to define how the person takes directions - how many assumptions the person does before start the job - how many questions the person asks (if asks) to make clarifications before start the job. Also, I see there another result - all answers come finally to two groups of getting result : 1) to get faster the first result but more steps for guaranteed result - from 1 to 4 steps or 1 to 4 weightings for combination 4+4+1 2) to get faster guaranteed result - from 2 to 3 steps for starting combination 3+3+3, I would say that BMF scheme contains one additional step (comparison of weight lighter/heavier - definition what of them is consider to be "odd" ), which in solution structure should be equal to the additional step, so it comes to from 2 to 4 steps but still in 2 to 3 weightings. After all, I would say that you may get from this question: How the person understand the task How many assumptions the person does before start the job How many questions the person asks before start the job How many solutions and ideas the persons generates. How the person make a choice to present one solution from multiple (say fastest first result vs fastest guaranteed result). Etc. The candidate should clarify if they truly mean the minimum to find the odd-weighted once, or everytime. I agree that it only takes one weighing (and some luck) to find it. Actually, the person could randomly guess (not weigh any) and get the right ball. So you need to understand the balance of risk vs. cost. By the way, simple logic problems do trip up people that you don't want working for you (depending on the job). So I like the question. It is interesting to speculate if the question wording is being cute or tricky by saying "more (or less)". Is it just being general and saying find the odd ball, or is it being tricky and saying find the odd ball AND tell me if it is lighter or heavier. I think it is being over thought here and just means find the odd. In that case the answers saying 2 weighings is the best you can guarantee. None of this lucky crap. BMF had it if you had to determine if it was in fact heavier or lighter instead of being told. So if the question had the added clause that if you really tried it and didn't get it in the number of tries you answered (or fewer), then you would be killed, would you still say "just one if you get lucky"? Keep it simple. If it's 3-state balance you need log2(9) / log2(3) attempts since you can encode 9 states using 2 3-bit states. I don't understand why everyone is confused. The question clearly asks to not only find the odd ball out but to also determine if the odd ball is lighter or heavier. The only assumption is that it is a standard two pan balance. My solution is 4 weighings: 1. Divide 9 balls in three groups of 3. Let's name them A,B,C 2. Weigh any two groups of 3. Let's say A and C. (1st weigh) 3. If A and C are equal then the B group is the culprit. 4. Now lets label the B group as B1, B2, and B3 5. Take either two balls from either A or C and measure against two from B let's say B2 and B3. (2nd weighing). If both are equal then B1 is the odd ball. Now weigh B1+ one good ball against the same two good balls used in the previous weighing and compare to see if the ball is heavier or lighter. (3 weighings) If they are not equal then determine if the B group is currently heavier or lighter. Go to step 6. 6. Switch either B2 or B3 with B1. Let's say we replaced B2 with B1. If the weighing is now equal then B2 is the odd ball out. If the weighing is still unequal then B3 must be the ball. Thus we have used a total of only 3 weighings. Since we made note of the weighing in step 5 we know if the odd ball is heavier or lighter. 7. Now if the 1st weighing (between group A and C) was unequal then we need to determine which is the bad group. Thus we need to weigh one of them against group B (which we know is correct) and then proceed with the steps 2-6. So in this case it is one extra weighing which brings a worst case total of 4 weighings. I hope everything made sense. I don't think its possible to get it in 3 AND also find whether the odd ball is lighter or heavier. One thing is for sure: I would have never solved it during the interview since this took way more than 5 min to figure out. I believe the answer is 2. Step 1: Before weighing anything, you separate the balls into groups of three. Step 2: Put one group of three on one side of the scale, and the other group of three on the other side of the scale, leaving still one other group of three somewhere on the side. ---visualization ooo /\ ooo <--------1st weighing ooo <------side group Step 3: If the scale is balanced that means that the heavier ball is in the side group. At this point, you would weigh any two of the remaining three balls. Again, if the scale is balanced, then you know that the only ball left is the heaviest one. If the scale tips to any particular side, on the other hand, then you know that the heavier ball is on that side. Up to this point the number of weighings is 2. Step 4: if on your first weighing with three balls on each side, the scale tips, then your next weighing will be of any two of the three balls which were on the tipping side of the scale. Again.. if the scale is balanced, then the remaining ball must be the heaviest. And if the scale tips to a side, then you know that side has the heaviest ball. Up to this point the number of weighings is also 2. Therefore the minimum number of weighings is 2. You obviously can get away with 1 weighing, but only if you are lucky; weighing 4 against 4 and hoping that the other ball (not weighed) is the heavier one. Otherwise, starting out weighing 4 against 4 will lead to 3 weighings, therefore that solution is not the optimal one. Even starting out with a 2 against 2 scheme, you can have up to 3 weighings until you are absolutely sure of which ball is the heaviest. So, optimally, you will be weighing 3 balls against 3, and the least amount of times you would have to weigh the balls to know for sure which one is heaviest is 2. In lieu of the fact that we don't know whether the ball is heavier or lighter then the rest, you would have to do 3 weighings. 1: ooo/\ooo ooo Do the first weighing as pictured above to isolate the set of balls that you know for a fact weigh the same. Then, in the second weighing, use that set to isolate the set that contains the odd ball. The second weighing should also tell you whether the odd ball is heavier or lighter because of how the scale reacts when you replace the control set with the unknown set. If the scale stays tipped down to the side opposite the control set, then it's heavier. If it stays tipped up, then it's lighter. If the scale was balanced before the second weighing, then you know that the remaining set is the set that has the odd ball, and replacing it with a set that you know all weigh the same should still tell you whether the ball is heavier or lighter by watching how the scale behaves. Then you can proceed to the 3rd weighing to isolate the heavier/lighter ball. So my mistake everyone -- the correct answer is 3 weighings when you don't know if the ball is heavier or lighter. Show More Responses I had this interview question this morning. Those of you who say it has no bearing on determining character are wrong. An arrogant person will present their answer, right or wrong, and say that they are done and it is perfect. It takes humility to consider that your first answer may be wrong, and the interviewer will want to see your process for checking that your answer is correct. Remember, it is the path you take to get to the answer that is more important than getting the answer right. Given 3 step, divide the balls into 3 groups A, B, C, Not knowing which has the heavier or the lighter ball, #1 Step: scale A vs B, If it balanced then we already know that C has the different weight.(but we still dont know if the ball is heavier or lighter. If it did not balance we will know that the OTHER ball is maybe in group A or B. (Note: e.g. A raises and B dropped) #2 Step: scale A vs C, If it balanced then we will know that the OTHER ball is in group B. If it did not balance e.g A raises and C dropped. we now conclude that C and B has the same weight and the OTHER ball is lighter #3 Step: Using the group A ball. scale the 2 balls, if they balance they we will know that the 3rd ball is the one that is different. if it did not balanced then the side where the ball raises is the OTHER ball because from step 2 we already notice that the ball is Lighter. Problem solved! Divide the 9 balls into groups of 3 3 - 3 -3 take first 2 groups on the scale. If they balance out: Take the last group of 3 Divide the last group into 1 - 2 Take the 2 (above) one each of the scale. If they balance out, then the '1' is the heavier one else u get the heavier one. Number of scale measurements required = 2 Balance 4 vs 4, - if balance the excess 1 is the lightest or the heaviest. Don't mind which is the heaviest nor the lightest since the question is OR - you can just have one answer. the minimum would be two. First ball and second ball either one would weight more... since they are asking the "minimum'... if they asked for the maximum then it will take 8 times. |

### Software Engineer at Facebook was asked...

You have two lightbulbs and a 100-storey building. You want to find the floor at which the bulbs will break when dropped. Find the floor using the least number of drops. 37 AnswersStart moving up in increments of 10 floors and dropping the bulb until it breaks (ie: drop from floor 10, if it doesn't break, drop from floor 20, etc.). Once the bulb breaks, move down to the floor above the last floor it broke on and start moving up floors in increments of one until the second bulb breaks. This results in a worst case scenario of 19 drops. Surely a binary search method would be more efficient i.e. starting at 50 and either going up or down 25 floors based on if it breaks or not. If you do a binary search, what happens if it breaks at floors 50 and 25? Show More Responses Do you know what a binary search is? You drop it from floor 12 next. If it breaks, you know it breaks between floors 12 and 1, inclusive. If it doesn't, you know it breaks between floors 13 and 25, inclusive. The main principle of binary search is that with each step you reduce your search space in half. Now your search space consists of only 12 floors. Wow, I want to get asked such a question in an interview! >>you drop it from floor 12 next... if you broke it on 50 and 25... you are out of luck and out of bulbs... 19 drops is not the best worst case scenario... imagine trying floor 16, if it breaks, you try 1 - 15 and thats 16 tries. if it doesn't break, then try floor 31 and if it breaks, then try 17 - 30 (so 16 tries, including the try on floor 16). And on and on (45, 58, 70, 81, 91, 100). If you reach 91, you'll have tried 7 floors so far and if it doesn't break, then there's 9 more tries to get to 100 (thus 16 in the worst case) Even a drop from the ceiling of 1st floor, a simple light bulb will break. thats what i think It's a light bulb. It will break when dropped from the 2nd floor. Drop it there then go to the first floor, hold it over your head and drop it. first do a binary search (agressive first step - fast) with 1 bulb. when first breaks, you know X(last but one fall - success) and Y(last fall - failure). now do a linear search starting from X(conservative but accurate second step - slow). complexity = in between logN and N. Use Binary search starting with the middle 50 The complexity of binary search is logN . So it will be log(100) < 7. Based on my experience, I think it will be floor 1 itself . Drop from 1st floor. If it didn't break, drop the same bulb from 2nd. If it still didn't break, drop the same bulb from 3rd... repeat as necessary. Only one light bulb required :) Yes, but doing each floor, that will give you the most drops -- question relates to optimizing for "least" number of drops -- I didn't think about being able to re-use the bulbs...that obviously is helpful. Maybe a fibonaci sequence once you determine a "break" floor and a "non-break" floor. I'd probably fail completely at coding it...knowledge of optimization and prediction theory would certainly be useful. Let f(m,k) be number of tries for m lamps and k floors. Obviously f(1,k)=k. let f(2,k) be s. k<=(s-1)+(s-2)...(1) =s(s-1)/2. Therefore f(2,100)=15. Show More Responses Actually, 16 is not the optimal, nor is 15; you can do it in 14. Here is one solution (there are at least 5 other equivalents): * Drop first bulb at 14th, 27th, 39th, 50th, 60th, 69th, 78th, 85th, 91st, 96th, and (optionally) 100th until it breaks. * Go to the highest floor where the first bulb didn't break. * Repeatedly go up one floor and drop the second bulb. When it breaks, you have your answer. Why is 14 optimal? Since you are decrementing each time, you want (n) such that sum(1..n) barely reaches 100. The answer is n=14. Generally, if the number of floors is (f), the lowest number of drops is ceil((sqrt(8*f+1)-1)/2). This is the best worst-case scenario. An interesting related question is what gives the lowest expected number of drops. And no, I could not have gotten this in an interview. In theory, use one bulb to determine an interval, and use the second bulb for a linear search within the interval. The solution that decreases the interval by one for each trial is quite clever. In practice, however, take the nature of the problem into account: Start on the first floor and move up by one floor. That's the answer I would be looking for. Start with bulb 1 and drop it from floor 2. Doesnt break? then floor 4 Doesnt break? keep dropping the same bulb moving even number of floors all the way upto floor 100. If on some even floor the bulb breaks drop the second bulb from the odd floor below the even floor, to detect if its the even or the odd floor that breaks the bulb Best case detection: 2 tries (first bulb breaks on 2nd floor, second bulb breaks on 1st floor) Worst case: 51 tries (the fist bulb breaks at 100 and second bulb breaks or does not break at 99th floor.. ) Go to the 100th floor and drop the first bulb. It WILL break. Done, 1 drop. It doesnt say whats the lowest floor it will break at, just at what floor will it break with least drops. Thus floor 100. Alright guys...you have two light bulbs. ...the second one has to be used for linear search, let the worst case number of items to be searched be x, then your interval will also have to be x, which will result a worst case of 100/x drops for the first light bulb. So now you are just trying to minimize n=100/x+x, find n'=0 when x=19...the candidate's answer is correct. I meant...x=10. and n=19. 0 drops, 1 bulb......stop thinking like computer nerds. Use physics or an engineering mindset. They didn't prohibit the use of any tools. Grab a scale, figure out force req'd to fracture bulb. Calculate acceleration due to gravity adjusting for air resistance/barometric pressure at location (trivial for anyone who took a 1yr physics course). Figure out how many meters up you need to be based on the req'd acceleration. Done.... @Rich: I am sure they were hoping for you to give them a computing answer since they don't do physics, and rather do computer science. mer's answer is correct: 14. Let F(s, n) be the optimal worst-case number drops for s stories and n bulbs. Suppose we drop at floor f, constituting one drop. If it breaks, we must make up to F(f-1, n-1) drops. If it doesn't break, we must make up to F(s-f, n) drops. Thus, for a given floor f, we have up to 1 + max { F(f-1, n-1), F(s-f, n) } drops. Optimizing over f: F(s, n) = 1 + min{ max { F(f-1, n-1), F(s-f, n) } for f in 1..s} Using the appropriate base cases, we have F(100, 2) = 14, as mer has given. Another way to think about it is in terms of decision trees. We want to construct a binary decision tree with leaf nodes for floors 1..100, and at most one "left" turn per path from root to leaf. To minimize the height of the tree, we want to reduce the variance in the length of each root-to-leaf path. This suggest we try dropping the first bulb at floors of the form: a, a-1, a-2, .. a-b, where the sum a + (a-1) + .. + (a-b) is equal to or barely over 100, so that determining almost any floor (possibly excluding the top few) takes a drops. Using this approach, we get the sequence of drops that mer has suggested. Well done @mer I have seen this question posed many ways, and that is the best answer I have ever seen. Sure hope I get asked this one now Show More Responses 14 In my experience light bulbs break when dropped from any height above 3 feet nice explanation from http://www.programmerinterview.com/index.php/puzzles/2-eggs-100-floors-puzzle/ Depends on how accurate u want to be. If i want exact answer, drop one from fifty, if it breaks start from first floor woth the remaining bulb. If it does not break, then start from fifty first florr. u will iterate fifty times as worst case. If u want a approximate answer, u can do binary way with give or take twenty five floors. Step over based on accuracy needed. You are all ignoring valuable information in this question. We are talking lightbulb, not bowling ball, and building, not step ladder. The bulb will almost certainly break by being dropped from the second floor (assuming US numbering conventions). The chance of it surviving a 3rd floor drop are miniscule, but not zero. The chance of a 4th floor drop, even less. Therefore, drop it from the 3rd floor first. If it breaks, go to the second floor and try. If that breaks you know the answer is 2. If it by some miracle doesn't break from the 3rd floor drop, the answer is 4, but take the elevator up one floor and drop it just to see. Rinse and repeat to 5, but since it will have already broken, go out and grab a beer, and tell your friends how much fun you just had. n*(n+1)/2 = 100. n approx = 14. In worst case u can figure it out in 14 drops. 14th, 27th, 39th, 50th, 60th, 69th, 78th, 85th, 91st, 96th, and (optionally) 100th until it breaks. I believe the number sequence should be: 14, 27, 39, 50, 60, 69, ** 77, 84, 90, 95, 99 **. The 9 floor gap between floor 69 and 78 would result in 8+8 = 16 drops worst case. Easy. Answer is zero. You don't need a test to find out that a lightbulb is going to break, even when you drop it from the first floor, because it's made of glass. BigO(100/X + X-1), Where X is the number of floors. 100/X calculates the dropping times to break the first one and X-1 is the additional maximum overhead to break the second one starting from the previous dropping floor to the floor the previous bulb was broken. If you solve the derivative of the above equation equal to zero, the optimal solution becomes 9.9 ~= 10 . Worst case = 100/10 + 10 -1 = 19 If its a glass bulb it will break from a 2ft height...i wont even care climbing any floors to check. Show More Responses Once you break the first light bulb, you are FORCED to start at the highest safe floor + 1 (i.e. highest floor that you safely dropped bulb #1 from) and drop bulb #2 one floor at a time, moving upward. Therefore, the algorithm for the first light bulb is critical (cuz once it breaks you are counting by 1's upward). Binary search starts at the 50th floor ==> max # drops = 50 Choosing fixed increments rather than binary search, e.g. start at 10, increment by 10, yields better results ==> 25 The ideal solution is 14 drops ==> Start at 14, increment by 14 each step until it breaks (leaving for the reader why 14 is optimal). It doesn't matter what floor you are on to make a bulb break. Doesn't it matter how high off the floor the bulb is dropped. If I am on the 5th floor and the bulb is sitting on the floor of the 5th floor, how high off of that 5th floor do I need to drop it before it breaks. This is a misleading question. The question doesn't say that you will drop the bulb out the window. Drop both from eye level. Both will break, and I answered the question without even climbing one stair. Efficiency isn't always about math..Common sense Answer: 14 drops Mathematically: 14 is the first number n, where the sum of numbers from 1 to n is greater than 100 Trial and error: The worst case happens when the bulbs break at floor 13. If you start from the 14th floor and the bulb breaks, then you start at the bottom floor and work your way up. If it doesn’t break and you try it again from the 28th floor and it breaks, then you go back down to the 15th and work your way up 1 floor at a time. |

### Software QA Engineer at Apple was asked...

There are three boxes, one contains only apples, one contains only oranges, and one contains both apples and oranges. The boxes have been incorrectly labeled such that no label identifies the actual contents of the box it labels. Opening just one box, and without looking in the box, you take out one piece of fruit. By looking at the fruit, how can you immediately label all of the boxes correctly? 38 AnswersAll the three boxes are names incorrectly. SO the bax lebeled Apples+Oranges contains only Oranges or Only Apples. Pick one fruit from it. If it is Orange then lebel the box as Orange. So the box lebeled Oranges contains Apples and the remaining contains both. Label the boxes fruit. The key bit is "All the three boxes are names incorrectly" so the label on the box which fruit comes from will need to be changes to one of the other 2 labels. It can only be 1 of them (and it will be obvious when you have the fruit) then the remaining box (that hasnt featured yet)...Just swap that label with fruit box that was originally on the box which you took the fruit out of Thats hard for anybody to understand somebody elses explanation... eaiest way is to just do an example Show More Responses Swaz answer is almost correct however it does not work in all scenarios. lets assume: box 1 is labelled Oranges (O) box 2 is labelled Apples (A) box 3 is labelled Apples and Oranges (A+O) and that ALL THREE BOXES ARE LABELLED INCORRECTLY" Pick a fruit from box 1, 1) if you pick an Orange: - box 1's real label can only be O or A+O - box 1's current label is O - since ALL LABELS ARE INCORRECT then box 1's real label can not be O - box 1's new label should then be A+O by elimination - since ALL LABELS ARE INCORRECT - box 2's label is changed to O - box 3's label is changed to A - SOLVED 2) if you pick an Apple: - box 1's real label can only be A or A+O - box 1's current label is O - since ALL LABELS ARE INCORRECT then box 1's real label can not be O - this still leaves us with the choice between label A and label A+O - which would both be correct - FAILURE Solution: The trick is to actually pick a fruit from the A+O labeled box Pick a fruit from box 3: 1) if you pick an Orange: - box 3's real label can only be O or A - box 3's current label is A+O - since ALL LABELS ARE INCORRECT then box 3's real label can not be A+O - box 3's new label should then be O by elimination - since ALL LABELS ARE INCORRECT - box 1's label is changed to A - box 2's label is changed to A+O - SOLVED 2) if you pick an Apple: - box 3's real label can only be O or A - box 3's current label is A+O - since ALL LABELS ARE INCORRECT then box 3's real label can not be A+O - box 3's new label should then be A by elimination (not O) - since ALL LABELS ARE INCORRECT - box 1's label is changed to A+O - box 2's label is changed to O - SOLVED it only says you can't look, doesn't mean you can't feel around or smell the fruit you picked, easy deduction after you figure the first box out Sagmi is right, but did not give the full reasoning. "the bax lebeled Apples+Oranges contains only Oranges or Only Apples. Pick one fruit from it. If it is Orange then lebel the box as Orange." so far so good Now, the box labelled Apples cannot be the box containing only Oranges, you've just found that box, so it must contain Apples and Oranges. And in that case the other box, labelled Oranges, must contain only Apples. It's easier to draw it out. There are only 2 possible combinations when all labels are tagged incorrectly. All you need to do is pick one fruit from the one marked "Apples + Oranges". If it's Apple, then change "Apple + Orange" to "Apple" The "Apple" one change to "Orange" The "Orange one change to "Apple + Orange" If it's Orange, then change "Apple + Orange" to "Orange" The "Apple" one change to "Apple + Orange" The "Orange" one change to ""Apple" Since all 3 boxes are labled incorectly Start with the box Labled A&O. If Its apples than the box labled apples then the apple one is oranges and the oranges is O&A. Label each box "Apples and/or Oranges" and the all will be correct. This is very simple to resolve. I was asked the same question at FileMaker. Each box is incorrectly labeled. So you go to the box that is labeled "Oranges and Apples" and take one out. It doesn't matter what comes out because all that you know is that it is not AO. If you remove an Apple then move the Apple label to it. Since the Apples are already identified it is easy to resolve the rest. All you know for certain is that the other two boxes remaining are mislabeled. So the AO label goes on the box with the remaining label and that label goes on the Apple box as you have already assigned that. The end result is you only need to remove one piece of fruit to figure out the proper locations of all. Go down the road to HP. Maybe they are hiring. Some of these pseudo-problem solving questions like this are bunk. I was once asked why sewer covers are round and not square. I gave the correct answer without even hesitation and the interviewer seemed put off that I knew the answer. I didn't get the job but, in hindsight, no great loss. I prefer the questions (like the basketballs one from google) where you won't be able to give an accurate numerical answer but by explaining HOW you would go about solving the problem is all you need to do and MAYBE shows your aptitude for problem solving. Smell the box you opened. Step 1: Order the boxes by weight. Either apples weigh more than oranges, or oranges weigh more than apples. The mixed box will always be in the middle. Step 2: Open the first box, take out the fruit and look at it. Step 3: If the fruit is an apple, deduce that the middle is apple and oranges and that the third box is oranges. If the fruit is an orange, then deduce that the last is the box with the apples. Show More Responses Donna is the only one with any common sense. The problem with corporate America, is that it's run by a bunch of Bozos who over complicate things and have a narrow to zero vision on how to solve even the simplest problems. I can imagine that most of you would get a committee, have long meetings where you talk about 'think out of the box', and 'at the end of the day' nonsense. This is an interesting logic question, but I would not want to buy fruit from a company who knew they had a problem and then sampled one out of three boxes to resolve the issue. There are other correct answers posted. I'll just make a comment: "The boxes have been incorrectly labeled such that no label identifies the actual contents of the box it labels." Nothing in the above statement says the labels are limited to oranges/pears, only that they do not identify the contents. They could say 'nuts', 'bolts', etc. Technically, all answers should be prefaced with: assume that the labels say 'oranges', 'pears', and 'orange/pears'. Ok, the problem does not make sense and is unsolvable if the labels say 'x', 'y', 'z', but someone with (likely with a math proof back ground) may appreciate attention to detail. Q: Why do posters denigrate the interview questions? The questions, however stupid they may be, are a opportunity to show you can build an answer. Even if you pursue an invalid train of thought in the interview, it's a thought. It's what they want to see and what will help you get a job offer. Note: I also would not assume that the questions asked are a reflection on the company, department, or team as a whole. It may just be the interviewer that has chosen poorly. So to say "I don't want to work for company X because they asked me a stupid interview question" is pretty closed minded. To even think I don't want to work with that interviewer just based on questions asked seems extreme. rightly pointed out by Sagmi ... this question was put forward to me at Huawei Technologies and that was the answer I gave So the question was asked at an interview for Apple: Label ALL the boxes apple and charge a ridiculous price for them! Just label all of them "Fruit." Put another way, it is not possible to tell since we don't know how the boxes are mis-labled. What if the Apple box was labeled Oranges and both the other boxes were labeled Apples and no box was labled Apples and Oranges? You might have assumed there are three different labels when their might have only been two different labels. Always pict a piece of fruit from the box labelled Apple&Orange. As we know that this label is wrong, there are two possibilities: If it is apple, then wo know that this box should be labelled Apple, so we switch Apple label with the label Apple&Orange. Then Apple label is correct. We also know that the Orange label is incorrect, so we then switch Orange label and Apple&Orange label. if it is orange, then we know that this box should be labelled Orange, so we switch Orange label with label Apple&Orange. Then Orange label is correct. The same as above, we know that the Apple label is incorrect, so we switch Apple label and Apple&Orange label. If all boxes are labeled incorrectly and u pick a orange out of a box that's labeled apple/oranges change the name to oranges then change the box labeled oranges to apples and the the box labeled apples to apple and oranges... If you pick a apple out of a box labeled apples and oranges change the name to apples and then change the box labeled apples to oranges and the last to apples and oranges... If u pick a apple out of a box labeled oranges change it to apples and oranges then the box labeled oranges to apples and the box labeled apples to oranges...if you pic a orange out of a box labeled apples change it to apples and oranges and the box labeled oranges to apples and the last to apples and oranges... See the pattern? I think there is a big box and it contain two small boxes and all the labels are incorrect so big one contain two boxes that makes it carrys both orange and apples and in that thwo boxes having orange and apple respectively so if we open any box we can label it correctly Show More Responses To see the java source code of puzzle, visit: https://github.com/SanjayMadnani/com.opteamix.microthon code is taking the input by console only. You can fork or clone the repository and proceed further. You can also rise bug if you find any. Run BasketPuzzleGameTest.java class as a Junit test case to start game. if it known already that boxes labeled incorrectly, I would give it back to those who did label them and ask to fix this confusion. it is impossible to tell by opening only one box, so you have to open one more box. As mentioned already, if you start with the A+O bucket, you can solve the puzzle by pulling only one fruit, Bucket: A+O Found: A Bucket A+O > A | A+O, but since A+O label is incorrect, then it must be A Bucket O > since A is taken, the new label must be O | A+O, but since O is incorrect, it must be A+O Bucket A > since A and A+O are taken, it must be O Bucket: A+O Found: O Bucket A+O > O | A+O, but since A+O label is incorrect, then it must be O Bucket A > since O is taken, the new label must be A | A+O, but since A is incorrect it must be A+O Bucket O > since O and A+O are taken, it must be A If you are lucky, you might solve it with just one fruit even if you start with other buckets, Bucket: A Found: A Bucket: A > A | A+O, but since the A label is incorrect, it must be A+O Bucket: O > A | O, but since the O label is incorrect, it must be A Bucket: A+O > since A+O and A are taken, it must be O Bucket: O Found: O Bucket: O > O | A+O, but since the O label is incorrect, it must be A+O Bucket: A > A | O, but since the A label is incorrect, it must be O Bucket: A+O > since A+O and O are taken, it must be A If you start with the A bucket and pull an O or if you start with the O bucket and pull and A, then you are SOL and you need to pull out more fruits to figure it out. 1. Open one box and check its contents. 2. Remove the current label and apply the correct one (by removing it from one of the other boxes) 3. Since all boxes have been labeled incorrectly, switch labels between the other 2 boxes. And Voila you have all the boxes labelled correctly :) In requirement already specify that all three box labels are not correct. A+O A O Step1: First Pick an item A+O Box. If you get an Apple then it is a Apple Box. swap the label . A A+O O AS we already know in the box that label with Orange, does not contain Orange because of wrong label. So It must contain A+O. Just Swap the label A O A+O OK, all 3 boxes are incorrectly labeled. Open the one that says apples and oranges. Whatever is in there is what it is (since it cannot be apples AND oranges). Now, if there was an orange in there, apples must be in the orange box (since they cannot be in the apples box), and apples and oranges in the apples box (due to process of elimination). Get it? I guess questions like these will appear easy if you put them on paper, it is the possible combinations that become relevant, one way to approach is.. One of the key factor is all boxes are labelled incorrectly, this gives rise to only (2) combinations right To label for 1st box incorrectly you will have (2) options, once you label it then you have only choice to label the other two boxes incorrectly so 2 x 1 = 2 combinations possible i.e. Incorrect lablling options { Boxes_with_Oranges, Boxes_with_Apples, Boxes_with_Apples&Oranges } = { A, AO, O} or {AO, O, A} 2. To know for sure the contents of the boxes, you need to pick the box with either Apples or Oranges and avoid box with Apples and Oranges. So from the (2) combinations you could pick a fruit from Box_labeled AO (this will contain either Oranges or Apples) So, if you get a Orange, it means that combination is{AO, O, A} , so that means Box_with_Label_O has Apples, Box_with_Label_A has Apples and Oranges Box_with_label_AO has Oranges or else if you get a Apple that combination is {A, AO, O}. Box_with_Label_AO has Apples, Box_with_Label_O has Apples and Oranges Box_with_label_A has Oranges Then you can correctly label all the 3 boxes. First answer in this post is correct, as its said all boxes doesnt reflect correct items in it, If an apple is picked from a box , then it can be from either A/O box or A box, if the box is names A/O the, the label of the box has to be changed to A, then other two box labels to be accordingly. It is interesting that in 6 years people keep overthinking this. The answer is in the question and the criteria are that the boxes are immediately labeled and they are labeled correctly. ANSWER: FRUIT FYI you don't even need to open one box. Show More Responses Your choice going to be (( 2 apple 1 orange)) or (( 2orange 1apple )) . It can be recognize only one box (x) . U have to chose again until u get another formula then u will named easly . Step 1: Open a box labeled ‘Apples and Oranges’. We know that this box does not contain ‘Mixture’ for sure. If this fruit is an apple, then label this box as ‘Apple’. Step 2: (Very important) If we look at the box labeled as ‘Oranges’, we know that since the label is incorrect, this box either has only apples in it or has Mixture. Since we already know which box contains only apples, we know that the box labeled as ‘Oranges’ contains ‘Mixture’. So label it as ‘Mixture’. Step 3: (Very easy) The 3rd box will be labeled as ‘Oranges’. When you put your hands on the box to pick the fruits by touching every fruits you can feel whether all are apple or oranges or both and just pick one to see.So it is not necessary to pick one fruit and see whether it is orange or apple also it is not said in question that you can touch and feel all the fruits inside the boxes without taking it out .and then you can fix the label correctly on the boxes. Absurd, no logic km I will took a pen and stab the apple. and then ? apple-pen. |

### Software Engineer at Google was asked...

Given the list of points of the skyline of a city in order (from East to West) Find the maximal rectangle contained in this skyline. I was asked to write the code. I managed to find the algorithm but was not sufficient. 21 Answersjust google for skyline. @Interview Candidate Have you found any particularly clear explanations? I'm working on a solution - I'll post it later tonight - but it'd be nice to confirm my understanding. Thanks. Clear? Well, to be more exact: Given N points on 2-plane: (x1, y1), (x2,y2), ... , (xN, yN) s.t. x1=0, xN= 0 and for all 10,yM > 0. Find the maximum value of the area of a rectangle inside the region bounded by these points and the x-axis. You can assume that the rectangle's edges are going to be parallel to the x,y axes. Show More Responses Here's an O(n^3) dynamic programming solution. It's pretty ugly, but it seems to work. More elegant/efficient solutions would be greatly appreciated. -------------------------------------------- import java.util.ArrayList; public class Skyline { private int maxX; private int maxY; public String[] findLargestRectangle(String[] points){ // First translate the points into a boolean matrix. // The cell [i][j] in the matrix should be true if // it appears under the skyline and false otherwise. boolean[][] cells = this.pointsToMatrix(points); System.out.println("Matrix is: "); this.printBooleanMatrix(cells,maxX,maxY); // Now we calculate rectangle size. Define // s[i][j] to be the size of the rectangle // with (i,j) at its upper left corner. int[][] s = new int[maxX+1][maxY+1]; int maxSizeX = 0; int maxSizeY = 0; int maxSize = 0; for (int i = 0; i maxSize){ maxSize = max; maxSizeX = i; maxSizeY = j; } } } System.out.println("Size matrix is: "); this.printIntegerMatrix(s,maxX,maxY); System.out.println("Maximum rectangle has size " + maxSize + "."); System.out.println("Its upper left corner is (" + maxSizeX + "," + maxSizeY + ")."); return null; } // Points to be given as "1 0", "2 5", etc. private boolean[][] pointsToMatrix(String[] points){ ArrayList list = new ArrayList(); // The maximum x-value will be that of the last point. maxX = Integer.parseInt(points[points.length-1].split(" ")[0]); maxY = 0; for (int i = 0; i maxY) maxY = y; list.add(new Point(x,y)); // Assume there are no duplicates } System.out.println("Points are: " + list); System.out.println(" maxX = " + maxX + ", maxY = " + maxY); boolean[][] m = new boolean[maxX+1][maxY+1]; int prevX = 0; int prevY = -1; for (int k = 0; k 0){ m[x][j] = true; j--; } } else { // Look left. If the cell to the left is false, then this cell // is true (start of rectangle top). The value of the cells below // is also true. // // If the cell to the left is true and the previous point had the same value // of x, then this cell represents the start of another rectangle. Set its value // to true and the values of the cells below to true. if ((! m[x-1][y]) || (prevX == x)){ m[x][y] = true; while (j > 0){ m[x][j] = true; j--; } // If the previous value of y is the same as this value of y and the // difference between x values is greater than 1, fill in the cells // in between. if (prevY == y && (x - prevX > 1)){ int i = x-1; while (i > prevX){ j = y; while (j > 0){ m[i][j] = true; j--; } i--; } } } // If the cell to the left is true and the previous point had a different // value of x, then this cell is false (end of rectangle top). Set it and // the cells below it to false. This cell may be inside another rectangle, // in which case its value will be reset to true. else { m[x][y] = false; while (j > 0){ m[x][j] = false; j--; } } } prevX = x; prevY = y; //System.out.println("After " + p + ", matrix is: "); //this.printBooleanMatrix(m,maxX,maxY); } return m; } (cont'd) private void printIntegerMatrix(int[][] b, int maxX, int maxY){ for (int j = maxY; j >=0; j--){ for (int i = 0; i =0; j--){ for (int i = 0; i <= maxX; i++){ System.out.print(String.format("%8b",b[i][j])); } System.out.println(); } } class Point implements Comparable{ int x; int y; Point(int x, int y){ this.x = x; this.y = y; } public int compareTo(Object o){ Point p = (Point) o; return (this.x != p.x ? this.x - p.x : this.y - p.y); } public boolean equals(Object o){ if (! (o instanceof Point)) return false; Point p = (Point) o; return (this.x == p.x && this.y == p.y); } public int hashCode(){ return x*37 + y*19 + x*11 + y*7; } public String toString(){ return "(" + x + "," + y + ")"; } } /** * @param args */ public static void main(String[] args) { String[] points = {"0 2","1 2","1 1","2 1","2 3","3 3","3 0"}; Skyline s = new Skyline(); s.findLargestRectangle(points); System.out.println(); String[] points1 = {"0 1","1 1","1 4","2 4","2 3","3 3","3 6","4 6","5 3","7 3","7 7","8 7"}; s = new Skyline(); s.findLargestRectangle(points1); } } Output: Points are: [(0,2), (1,2), (1,1), (2,1), (2,3), (3,3), (3,0)] maxX = 3, maxY = 3 Matrix is: false false true false true false true false true true true false false false false false Size matrix is: 0 0 3 0 2 0 2 0 3 2 1 0 0 0 0 0 Maximum rectangle has size 3. Its upper left corner is (0,1). Points are: [(0,1), (1,1), (1,4), (2,4), (2,3), (3,3), (3,6), (4,6), (5,3), (7,3), (7,7), (8,7)] maxX = 8, maxY = 7 Matrix is: false false false false false false false true false false false false true false false false true false false false false true false false false true false false true false true false false false true false false true true true false true true true false false true true true false true true true false true true true true false true true true false false false false false false false false false false Size matrix is: 0 0 0 0 0 0 0 7 0 0 0 0 6 0 0 0 6 0 0 0 0 5 0 0 0 5 0 0 4 0 4 0 0 0 4 0 0 9 6 3 0 9 6 3 0 0 6 4 2 0 6 4 2 0 4 3 2 1 0 3 2 1 0 0 0 0 0 0 0 0 0 0 Maximum rectangle has size 9. Its upper left corner is (1,3). Found bug: public *int* findLargestRectangle(String[] points){ ... *return maxSize*; } (obviously) I don't mean to discourage you but there is no way that you can get away with an answer that works in O(N^3) for this question and even if the interviewer was happy with this performance, it would be impossible for you to write this kind of code given a reasonable time limit for the interview (which is around 45 minutes, and that's the entire interview which includes introduction and possibly some other easy questions) You can solve this in O(N). I don't have time to write a solution right now, I strongly recommend looking at Topcoder's skyline problems and contestants' solutions for an insight. best of luck to you For others' reference: http://www.topcoder.com/stat?c=problem_statement&pm=7473&rd=10661 http://www.topcoder.com/tc?module=Static&d1=match_editorials&d2=srm337 https://www.spoj.pl/problems/HISTOGRA/ http://www.informatik.uni-ulm.de/acm/Locals/2003/html/judge.html Here's a much nicer O(n^2) solution. As Anonymous said, there's an O(n) solution, too. /* * In this input array a, the ith building * has height a[i], which means its lower left * corner is at (i,0) and its upper right corner * is at (i+1,a[i]). All buildings have width 1. * The total width of the skyline is n. */ public long getMax(long[] a){ int n = a.length; int[] leftWidths = new int[n]; int[] rightWidths = new int[n]; // For each building, check how many units width to the left of the // top block of this building we can move before we are no longer // in a building. for (int i = 0; i = 0) && a[x] >= a[i]) { x--; count++; } leftWidths[i] = count; } // For each building, check how many units width to the right of the // top block of this building we can move before we are no longer // in a building. for (int i = 0; i = a[i]) { x++; count++; } rightWidths[i] = count; } // Now find the maximum rectangle. The value of the ith building's // rectangle is its horizontal width times its height, or // (1 + leftWidths[i] + rightWidths[i]) * a[i]. long maxArea = 1; for (int i = 0; i maxArea) { maxArea = nextArea; } } return maxArea; } O(n) solution: /* * Basic idea: use a stack to store the buildings. Look at * the buildings in left-to-right order (west to east). If a * building is taller than the building on the top of the stack * (the tallest building to its left), push it onto * the stack. If a building is equal in height to the building on the * top, skip it. If a building is shorter than the building on the top, * it is not part of the maximum rectangle that is topped by the tallest * building to its left. Pop that tallest building, calculate its area and * compare it to the current main area, then repeat the comparison * procedure with the new tallest building. * * Along the way, track the number of buildings to the left and right of a * given building that would participate in that building's maximum * rectangle. The number to the left is equal to the number of buildings * that are popped off the stack before this building is pushed - that is * the number of buildings to the left of this building that are taller. * We do not need to worry about the buildings that are equal in height * since they are discarded (they are accounted for in the topBuilding's * rightWidth count). * * The number of buildings to the right of this building that participate * in this building's maximum rectangle is equal to the number of buildings * that are discarded because they are equal to this building's height * plus the number of buildings that are pushed onto the stack because they * are taller than this building while this building is on the top of the * stack. * * In this input array a, the ith building has height a[i], which means * its lower left corner is at (i,0) and its upper right corner is at * (i+1,a[i]). All buildings have width 1. The total width of the skyline * is n. */ public long getMax_useStack(long[] a){ Stack stack = new Stack(); int n = a.length; long maxArea = 1; // Process the buildings in left-to-right order. for (int i= 0; i < n; i++){ Building nextBuilding = new Building(a[i]); // Keep track of the number of buildings that we pop before we // push nextBuilding. That number will be equal to the number // of buildings to the immediate left of nextBuilding that are // taller in size. int popCount = 0; // If the stack is empty, push the next building onto the stack. // There are no buildings to its left, so we do not need to // update nextBuilding.leftWidth. if (stack.empty()) { stack.push(nextBuilding); continue; } (cont'd) // Otherwise, compare the new building's height to the building on // the top of the stack until the new building is either // discarded (if it is equal in size) or pushed (if it is taller). while (! stack.empty()){ Building topBuilding = stack.peek(); long heightDiff= nextBuilding.height - topBuilding.height; // If the new building is equal in height, skip it. Increment // the rightWidths count of topBuilding as its largest // rectangle goes through the new building. if (heightDiff == 0) { topBuilding.rightWidth++; break; } // If the new building is greater in height, push it onto the // stack. The number of buildings to the immediate left of it // that are taller is equal to the number of buildings that // were popped before this point, its popCount. Set its // leftWidth equal to its popCount. Increment the rightWidths // count of the top building as its largest rectangle goes // through the new building. if (heightDiff > 0) { nextBuilding.leftWidth = popCount; topBuilding.rightWidth++; stack.push(nextBuilding); break; } // If the new building is less in height, update the maximum area // with regards to the element at the top of the stack. long topArea = topBuilding.getArea(); if (topArea > maxArea){ maxArea = topArea; } // Then discard the top element and repeat the comparison // procedure with the current next building. stack.pop(); popCount++; } } // If all buildings have been processed and the stack is not yet empty, // finish the remaining subproblems by updating the maximum area // with regards to the building at the top of the stack. while (! stack.empty()){ Building topBuilding = stack.pop(); long topArea = topBuilding.getArea(); if (topArea > maxArea){ maxArea = topArea; } } return maxArea; } class Building { long height; int leftWidth; int rightWidth; Building(long y){ this.height = y; leftWidth = 0; rightWidth = 0; } long getArea(){ return height * (1 + leftWidth + rightWidth); } } ellemeno, Nice solution/explanation. However, maxArea should be initialized to 0. @logimech Right. :) Thanks. Show More Responses ellemeno: The program has bug. We need to store the building's x cordinate. And when the nextbuilding is shorter than the top one, we need to update each popped building's rightwidth as topbuilding.x - nextbuilding.x Isnt this the convex hull problem? The O(n) algorithm does not work. I have another solution for it, however. Suppose we have the array of heights a of length n. We are looking for the smallest building index (let's say x and divide the problem in 2: the left part ( between 0 and i - 1) and the right part (between i + 1 and n - 1). Then we compute the area that can be build using the building indexed with i: a[i] * (n - 1 - 0 + 1) = n * a[i]. We compare this area with the ones obtained from the left and from the right part and return the result. Therefore, the complexity will be: N * time to find the index of the smallest building in a range - which is RMQ problem that can be solved in O(logn) and O(n) preporcessing time (and O(N) space). Therefore, the complexity is O( N log N). It works for 3 6 5 6 2 4: the solution is 3 * 5 = 15. The problem is known as the biggest rectangle below a histogram. An old question with my answer. using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SkylineTest { class Program { static void Main(string[] args) { Point[] pointList = new Point[10]{new Point(0, 1) ,new Point(1,1) ,new Point(1,2) ,new Point(2,1) ,new Point(2,2) ,new Point(2,0) ,new Point(4,0) ,new Point(4,6) ,new Point(5,6) ,new Point(5,0)}; Skyline sl = new Skyline(pointList); Point maxPoint = sl.CalculateMaxRanctangle(); Console.WriteLine("MaxPoint:" + maxPoint.X + " " + maxPoint.Y); Console.WriteLine("MaxArea:" + sl.MaxArea); Console.ReadLine(); } } public struct Point { private int _x; private int _y; public int X { get { return _x; } } public int Y { get { return _y; } } public Point(int x, int y) { _x = x; _y = y; } } public class Skyline { private Point[] _pointList; private int _maxArea=0; private Point MaxRactanglePoint; public int MaxArea { get { return _maxArea; } } public Skyline(Point[] pointList) { _pointList = pointList; } public Point CalculateMaxRanctangle() { Point maxPoint = new Point(0, 0); for (int index = 0; index 2) { for (int i = index - 2; i >= 0; i -= 2) { if (_pointList[i].Y >= _pointList[index].Y) areaForPoint += (_pointList[i+2].X - _pointList[i].X) * _pointList[index].Y; else break; } } if(index= _pointList[index].Y) areaForPoint += (_pointList[i].X - _pointList[i-2].X) * _pointList[index].Y; else break; } if (areaForPoint > _maxArea) { _maxArea = areaForPoint; maxPoint = _pointList[index]; } index += 2; } } return maxPoint; } } } i dont know if i understand the assignement correctly, but shouldnt ne sufficient to iterate all coorfinates and find min x, min y, max x, max and then calculate the area given by this rectangle? Hi Guys, there is O(N) solution using STACK. http://www.geeksforgeeks.org/largest-rectangle-under-histogram/ Psuedocode //Iterate through points one time where a point further east is greater than a point farther west, a point higher up is greater than a point lower down. //if x greatestX, greatestX = x //if y greatestY, greatestY = y //Equate (greatestX - smallestX) by (greatestY - smallestY) For some reason that left out like half of my psuedocode |

### Software Engineer at Cerner was asked...

The only unexpected question was to design a employee database because it wasnt in the previous thread :) but it was easy 18 Answersplease reply... Are they expect coding or UML diagrams for chess game ? No .. No uml or coding .. Just the high level design sorry, i don't understand.could you please explain it,programming design means UML.am i right.? what is high level design here.. Thank you in advance. Show More Responses They will just ask you that what classes will u use .. So just list the classes and if u wil make any abstract class or interface .. That's all they expect no uml or class diagram is needed Thanks, Hi, Could you provide some test cases for the following question? I am not very familiar with writing test cases. I would greatly appericate your help. Unit test a function which uses the following parameters : reversestring(originalString, stringToBeReversed, stringReverseTo,max) (Come up with as many test cases as possible) All you need to do is pass some actual values in the arguments, you can write as many combination of values as you want, for ex: in the function reversestring(originalString, stringToBeReversed, stringReverseTo,max) you can write test case as reversestring('abcde', 'abc', 'opr', 2) try to put some negative test cases too, ex: reversestring(1234566,33,4,2) reversestring('','','', ) Hi, Can you please provide some answers to this question: How do you find a bug and what steps did you take to correct it? Can we just say we will create a bug report, debug the code etc... or are they looking for any specific answer? Please do reply Thanks in advance Design an unbalanced BST using the word "CERNER" , duplicates allowed. - Can you please give me the right way of constructing this? Thank you. C \ E \ R / N / \ E R I was unable to find preorder traversal for the above one :(, however the following one gives proper solution for all pre, in, post order traversals. What do you suggest? C \ E \ R / \ N R / E Thank you very much. You are right I think the last solution you gave works fine for the traversals. Hi, Can you please provide some answers to this question: How do you find a bug and what steps did you take to correct it? Can we just say we will create a bug report, debug the code etc... or are they looking for any specific answer? Please do reply Thanks in advance Show More Responses Hi I have Question on Salary.I know it is not appropriate to ask this.But,If Possible anybody please answer. How much they offered to 1+ years experience.?(between 70k-75K or 75k-80K). Thanks in advance. are you experienced or did you apply for entry level positions ? https://dev.mysql.com/doc/employee/en/sakila-structure.html Can you explain unit test case for Stringreverse To which positions do we need to apply for software developer? |

**21**–

**30**of

**37,559**Interview Questions

## See Interview Questions for Similar Jobs

- Software Engineer
- Software Developer
- Senior Software Engineer
- Java Developer
- Software Development Engineer
- Senior Java Developer
- Associate Software Engineer
- Java
- Senior Software Developer
- Software Engineer Intern
- Intern
- Junior Software Engineer
- Principal Software Engineer
- Software Engineering
- Software
- Software Engineer I
- Java Engineer
- Web Developer
- Entry Level Software Engineer