Engineering Interview Questions
engineering interview questions shared by candidates
Top Interview Questions
You are in a boat in a pool with a rock in your hand. You throw the rock into the pool. Does the water level rise, drop, or stay the same? 14 Answersdepends on how big the pool is and how accurately you can measure the water rise you're already in the pool with the rock, so the water displaced is the same...this other guy is stupid If the rock were neutrally buoyant the water level would remain the same. It is heavier than water which causes it to displace more than its own volume while in the boat compared to at the bottom of the lake. Therefore the water level of the lake would go down. Show More Responses At the moment the rock leaves your hand the water falls in the pool. When the rock enters the water the water level of the pool rises again to the level it had before you threw it. really? I thought the water would go up ? These answers are troubling. The only correct answer so far is Ben. The water level goes down. I'm not a mechanical engineer, but I did stay in a Holiday Inn Express last night. I hope no one else who has answered this question here (except for Homebrook) is a mechanical engineer. When you add the volume of the rock and subtract the volume of water previously displaced by the boat+rock, there is no change in the water level of the pool. Another way to answer is: The water level measured at the side of the pool remains the same. The boat becomes more buoyant and the water level measured at the side of boat falls. The weight of the boat plus you plus the rock has already displaced the height of the water. The only time the water level will change will be when the rock is mid air. M no Bbbbbbbbbbbbbbbbbbvvbvbbvbbb. B.B. BNb. Bbbb Bbvbbbbbbb Bbbbbbbbb B.B. Bbbbb V bbbb BNb B.B. BNb Bbbbbb BNb BNb Bbbb. BNb B b. Bbbbbbbb. N n. Bbbb. B B.B. N BNb bbb Nnnnn Nnnn nnn Nnnn Nn N. Nn N M Mm. I. N. M M m Mmm n nnn Mmm mmnmmmnm Mmnmmmmm Mmm my Mmmm Mmm Mmm Mmmmmmmmm m Mmmmmmmm It will raise by the same volume of the rock. First time, the water buoyant force is equal to the mass(boat + person + rock).g /subsequently, the water got displaced was also that much, the water level on the pool will be higher. second time, since rock is gonna deposit down to the bottom of the pool, it'll be like: water displacement = (boat + person).g + the volume of the rock (but it's probably much less than the water displacement it could have created when it's on the boat). There is no way that rock is displacing the same amount of water as it did previously. (1kg gold (Density: 19.30 g/cm3) and 1kg silver(Density: 10.49 g/cm3) in normal situation has different volume, so when deposited to the bottom, silver will displace more water than gold, yet both displace less water than when rock was sun-bathing on the boat) In conclusion, first time the water level was higher both on the pool wall and the mark on the boat, second time it'll be lower on both end. Depends on how big the rock is Show More Responses More weight on the boat = more displacement, while throwing the rock overboard would still displace water, the overall water lever will fall. Since the rocks surface area is smaller than the boat. One or more comments have been removed. |
They asked me how I would deal with an irate patient/customer. 1 AnswerI personally think the number one thing to do is to listen to them to them. Show them that you are interested in remedying there issue. People just want to be listened too. |
What is a typical sales call for you? 1 AnswerI would focus on entertaining clients and finding their motivations and needs. I spent too long talking about end-user type sales and solving their problems, reacting to unexpected events, etc. |
Engineering at Qualcomm was asked...
given 20 "destructable" light bulbs(which breaks at certain height), and a building with 100 floors, how do you determine the height that the light bulb breaks. 56 Answersbinary search start at the top floor and work down toward the first floor to see on which floor the bulb breaks first Start at the lost likely point based on your experience – the first floor -- and see if the bulb breaks when dropped. If not, then a test is warranted. Start at half way point and keep going up or down to the next halfway point until you determine the height. You should be able to determine the floor within 7 bulbs or fewer and – assuming each floor is 10 feet high, you should be able to determine the exact height in feet within another 5 bulbs or fewer. The greatest number of bulbs you could break to reach the answer would be 12, plus the one for the initial test = 13 total. Show More Responses In my interview at Apple, this question also stated: "You will get a bonus of $1000 for each remaining glass bulb after the test. What is the highest bonus you can absolutely guarantee, and with what algorithm?" The interviewer told me that he only had it answered correctly once, and that person had a master's degree in pure mathematics. The candidate explained the theory behind the answer using lots of appropriately mathematical terms. The long-winded, logic-based solution to prove that you can earn an $18'000 bonus goes as follows: • If you drop a ball from floor X and it shatters, you will need to drop the other from floors 1 to x-1 in that order to find out the lowest floor at which the ball would break. • Therefore, if you started at floor 20 and the ball shatters, you have to drop the other from 1 to 19 to see at which that one will shatter. • If it shatters at floor 19, your bonus is all gone (you're performed 20 drops, losing $20'000 from your bonus). • If the ball does *not* shatter at floor 20, then you might try again at floor 40, but then you'd only have 18 drops left— if it broke at 40, but not at 38 (when you've used all your drops) you don't know if 39 or 40 was the breaking-point. • Therefore, after trying 20, you go up 19 floors to 39 and try again there. • You repeat, going up 18 floors to 58, then 77, then 86, etc. • However, this isn't optimized. You can't *guarantee* a bonus by stepping up by [20 19 18 …], since you could conceivably deduce the amount only using a full 20 drops. • Therefore we look at how we can divide up our 100 floors by a descending sequence: • 10 + 9 + 8 + … = 55 => No Good. • 11 + 10 + 9 + … = 66 => No Good. • Try going the other way; starting at 1 and counting up (sort of like the Fibonacci sequence), at which point do we pass 100? • 1 + 2 + 3 + 4 + … + 12 + 13 + 14 = 105. • Therefore, we can start dropping the ball at floor 14 using the algorithm above, and still have enough drops to determine the exact floor at which the ball breaks, even should it be floor 99 or 100. • Using 14 as a base, this means that the *maximum* number of times we will drop the ball is 14 times, while still guaranteeing that we drop at $BREAK_HEIGHT and $BREAK_HEIGHT-1. Therefore, the correct solution can be calculated using only two glass balls, a maximum of two of which will smash, guaranteeing us a bonus of $18'000. QED :o) Only one light bulb is needed. Start at floor level, drop it, and if it does not brake USE THE SAME BULB for next trial higher up until the very same bulb brakes. One light bulb is not sufficient because even if it does not break, after one drop, it will become more fragile, thus may break at a lower floor than a new bulb. Thus a different bulb should be used for each drop. BTW, there is a closed formula giving the maximum number f of floors for which one can find the height with a given number b of bulbs and a given number w of bulbs that can be broken (and the algorithm can be deduced at the same time). This is probably a well-known combinatoric problem. If the balls do not weaken, then one ball is sufficient and the guaranteed bonus is $19,000. If a different ball is required for each drop, then binary search will find the height of breakage with 7 drops or less (2^7 = 128 > 100), so the guaranteed bonus is $13,000. I believe it can be proven that you can't guarantee better than this. Take the stairs... 1. the question does not say they break when you drop them, it could be air pressure. The question needs clarification 2. the question does not say the bulbs are all the same The question was about light bulbs not about the building or its height. I would get $19000. Take a bulb hold it ,say, 1 inch above a hard surface. Drop it. If it does not break try 2 inches keep adding a inch until it breaks. Nothing was said about testing it from a floor. I could also drop it on a very soft surface and if soft enough make the $20000. Sometimes we think too much. You were misdirected. Take the elevator or walk up the stairs with just 1 light bulb. Once it breaks, check the floor number in the elevator or number on the stair well. You get $19,000 if it breaks, you get $20,000 if it never breaks. You never need 20 light bulbs in the first place. The bulb always breaks against the tarmac so you don't even need to go to the top, just know that the bulb breaks at 0 Show More Responses This is a Newtonian math question. Go to the 50th floor. Does the light bulb break? if yes go to the 25th floor. If no go to the 75th floor. If on the 25th floor the bulb breaks go to the 12 floor if not go to the 37 floor. If on the 75th floor and it breaks go to the 62 floor. If it does not break go to the 87 floor. Basically you continuously do an break vs. not break analysis and divide the most recent floor delta by 2. If it breaks subtract the value from your current floor and go to that floor. If it did not break add the value to your current floor and go to that floor. This is the most efficient way (uses the least amount of bulbs) to find the highest floor that the light bulb will not break. I think Apple took a good approach, but in general, the follow-up question to this one is more interesting, and one I would look for: What is the desired OUTCOME? There are a number of ways to determine the correct floor. But in most tasks, there are desired outcomes. Does the questioner wish the most efficient way to determine the floor number (that's not in the question)? Or does the questioner care more about having extra light bulbs at the end? People often jump into the programmatic solution first, without ever thinking to ask "What should my end state be?" Agree with Andrew and Anthony........start walking down the stairs with one bulb. When it breaks you have your answer. 19 left. I hold a light bulb with care because I know it will break if I drop it. I would question the competence of marketing for wanting to determine height of destruction of a light bulb. I would ask that they just slap a "fragile: contains glass" label on the package and shift resources to R&D to create a light bulb that burns longer and uses less energy because that is what people really care about in light bulbs. Read the manual people!!!!or call the company manufactoring those bulbs!!! 20k in the bank. I believe the answer to the question lies simply in the asking. The point is to get these responses, and more importantly put you into a different frame of mind. You are no longer providing canned responses to generic questions but are now faced with a situation or question that requires novel thought process. Again the answer is not necessarily important, but the result is. You could put all 20 bulbs in a box and start walking up the stairs. Label each bulb as to what floor you were on when it broke. Is this too simplistic, or am I missing something?? Why are alot of people dropping the bulbs. A bulb will most likely break when dropped from almost any height. Who is the Einstein who said to start at the top floor. I think most of the bulbs would already be broken if you were on the tpo floor to start with. Nutbags!!!! In response to Jim, I think you can actually figure it out with only lightbulb lost. Assuming you started from the bottom floor and worked up to the top floor dropping the bulb and then picking it up and dropping it again on the next floor. It would take quite a while though. That is assuming you want to optimize the number of bulbs lost. If you want to optimize based on time, you would want to do a binary search algorithm All of these answers implies two (2) important facts being overlooked. Fact one - no one said you couldn't pick up an unbroken bulb and try it again. Fact two - no one said you had to drop the bulb. It just said "breaks at a certain height." None of you considered that...maybe by ascending the building carrying one (1) bulb...it might just...break? Convergent thinkers!!! Show More Responses I would first correct the grammar in the statement: "how do you determine the height *that* the light bulb breaks..." to "the height *at which* the light bulb breaks..." and proceed to not get the job. Why would you need to know that? The BA in me would seek clarification in the requirements. The questions being asked is unclear. A) Does the question mean the bulb would break if placed on a certain floor of the building or is the asker really meaning the bulb would break if dropped from a certain height? B) Is the goal to find the most efficient solution to the question (i.e. fewest number of tests)? C) Assuming we are dropping the bulbs from the building, can we collect unbroken bulbs and reuse them? Without this information, there is no way to answer the question. The answer depends on this additional information. Simple: Do a Bruceton staircase analysis. This method is used to determine the mean failure height along with a confidence interval ("95% confident that 50% will fail at floor x") and percentile ("99% will fail by floor y") of packages all the time. It also takes into account variations in bulb fragility and minimizes the chance that you have a "bad" light bulb that was more fragile and thus failed early. The one I'm going to cram up your bum for wasting my time... Me: Throw a bulb off at 50th floor, if it breaks go to the 25th. If it breaks go to the 12th and test out a bulb. At that point you have 18 bulbs and about 11 or 12 floors to test either above or below the 12th floor. The same applies if the bulb does not break at the 50th floor, try 75 and follow the same procedure. work from bottom up and throw one at every 10 floors. if the light bulb breaks at this throw, then work downwards and throw at each floor to determine the exact point where the light bulb will break? is it really that hard?? I will go with Bruce! Given the condition that Jim Dovey added in above comments, if one is going to get bonus of $1000! algorithm depends on what you want to achieve. 1. Optimize number of trials: Solution- use binary search approach. guaranteed bonus=13k 2. optimize profit: solutino - start from 1st floor. go up one level. Only 1 bulb needed. guaranteed bonus = 19k CG Your logic is interesting. But when you say (uses the least amount of bulbs) your word usage is incorrect. Amount is for a measured quantity as in amount of sugar. You should have said (uses the least number of bulbs) or (uses the least bulbs) Number is for counted quantities It's funny, variations of this question are so common in the industry I'm currently in that it's become a parody of itself...the answer I gave for an app engineer job after hearing it from the 11th different firm: "I'm not answering it for the same reason you Googled the questions to ask: neither of us have time for this." I kind of just blurted it out. As you might expect, I wasn't offered the engineer position. I was instead offered the group supervisor position. I would not try this at home -- but they told me they'd never had anyone answer it that way, and it was the reason they made me that offer. It's an extreme example of how these questions are as much about attitude as aptitude. Show More Responses $19,000 bonus and one bulb is enough - drop as follws 1,3,6,10,15,21,28,37,47,58,70,83,97 contune untill all 1-100 distances are covered. We can reduce trials and sacrifices some bonus, if each trial cost something that will impact bonus DownOn3 has it. The question didn't say anything about dropping. It said the bulb will break at a certain height, I'll say that means it will break at a certain atmospheric pressure. Take one bulb, leave the rest at the bottom of the building. Walk up the stairs until the bulb breaks. At most, one will break. $19,000 bonus guaranteed. Divide the # of floors in half each time and go to the nearest whole #. Drop a bulb from that floor, then go the next 1/2 way point (50, 12 or 25, and so on). If this is not an atmospheric/pressurization question, all bulbs will break at a height of 0. I'm not even going to waste a bulb on that one. There would be questions before doing the test. What is more important to save time or save bulbs? (Similar question as what is more costly the light bulbs or my time?) If they are experimental bulbs that cost $1000 each, I'm pretty sure I could walk to eah floor in less than 16 hours (and unless I get payed $1000 an hour) then it is more economical to go up one floor at a time (although I would not quite do that). If the bulbs are cheap (let say $1 each) then my time is more expensive. So the number of times over 1 that I drop it an it does not break is wasted time (or money). Then I would use a binary search algorithm. Also if there is an elctro magnet attached to a cable it may help in making the test shorter (ideally it needs to be 25 stories in length). How accurate do the findings need to be? (down to a floor or down to an inch). BTW, the minimum number of bulbs that would need to be destroyed is 3. Since the experiment (yes, it is a scientific experiment) needs to be verified at least 3 times. BTW, LED light bulbs are very tough is is essentially a piece a piece of metal inside a piece of plastic. This bulbs are tough. I have drop an entire fixture from 20 feet (bulbs and metal casing) and it survived. So for those who "ASSUMED" that all bulbs break at distance greater than 0. Thank you for applying, but the management positions are already taken, they were looking for an engineer. As I can tell many people here are not the core group Qualcomm was looking for. This is similar to a question on the published "Cracking the coding interview" on chapter 6.5 in the "Brain Teaser". It is on P96 in 5th edition. Given 20 destructable light bulbs and a 100 story building.... You know what? I don't need this job anymore, I have a 100 story building now!!! I'll stand at the base of the building and smash a lightbulb into the floor. If it breaks, problem solved. If it doesn't break then I'll start taking steps up the stairwell banging on the lightbulb on each step. You only need one light bulb to figure out at what height it breaks, assuming that they're all the same. I generally agree with all the people that say that the lightbulbs break at a height of zero though, assuming that you're dropping the lightbulbs off the building FROM any height. The question wasn't what height the bulb breaks when dropped FROM. Obviously the height that the bulb breaks is ZERO when it hits the ground. But that's assuming that you drop it on the ground next to the building and not on each of the 100 floors. Then again, the bulbs might break at EVERY height. If you so much as touch these light bulbs they will break, let alone drop them! Maybe these lightbulbs and the new high-tech ultra-thin glass breaks in anything short of an absolute vaccuum and zero gravity. Maybe this really is an altitude issue. Maybe your 100 story, 350-foot tall building is insufficient and irrellivent because the bulbs break at an altitude of 35,000 feet. Also, every single one of you assumed that you recieved these light bulbs intact. Maybe to answer the question you simply need to look at the light bulb where it already lies in pieces on the floor. Alternatively, these could be self-destructable lightbulbs with an altimeter and an explosive charge built in. Walking up or down the stairs holding one of these lightbulbs would be suicide. The question then would be what might motivate you to figure this out if it would cost you your life? First read the question and figure out what is being asked, then think outside the box. The question states that the bulbs break at a certain height. That is, not when you drop the bulb from that height, simply that they break at that height (presumably due to air pressure?)... I lose zero bulbs. Simply wait until evening and look up. The number of floors that have lights turned on will tell you which floor they start breaking at. Show More Responses Well I don't see how the number of floors of the building matter. It doesn't ask what floor you need. It asks at what height will the bulb break. Therefore, you just need to know the height at the time the bulb breaks, not what height it was dropped from. You need final height, not initial height. No matter the initial height, the final height will always be the ground. So the height will be zero when the bulb breaks. And I didn't even need a formula! :-) The question does not mention why the bulbs would break. The only reason a bulb would just break at a certain height without impact is because of air pressure. Bulbs are in a vacuum and because of the shape of a typical bulb, positive external pressure will not be a factor. However, a negative external pressure may have an effect depending on the pressure inside the bulb. Also varying barometric pressure will also have an effect. On a bright sunny summer day, the bulb would burst at a greater height. On a cloudy day the barometric pressure is lower so the bulb would burst at a lower height. And the question does not ask for height above sea level or above ground level. This is an open-ended question that leaves for more questions than answers. But if I really want to come up with an definite answer, I would say the "certain" height is the height at which I smash the bulb. So if I am in a building that has a foundation 535 feet above sea level and I smash the bulb on the 100th floor and each floor is 12 feet above the one below: (12 X 99) + 535 = 1723 feet. You do not add 12 feet for the 100th floor because the 1st floor is 0 feet above 535. actually its very hard to understand the question only .. and d ans given here all crap // guys atleast if u dnt knw d ans plzzz dnt give your opnions.. ty It needs just 2 bulbs to efficiently know the floor from where it will break. Assume you have just 1 bulb, then there is no other way to test except trying it one by one from each floor. i.e. start with 1st, if it breaks, well, we know the answer, otherwise go to the next... Now take 2 bulbs...go to the 1st floor, throw one bulb at ground and the other at the height of 2nd floor at the same time. If 1st bulb doesn't break and second one breaks, then 2nd floor is the answer, and we knew it in just one attempt. If neither of the bulbs breaks, we need go to 3rd floor, as we tested already for the 2nd floor. And from 3rd floor, throw one bulb at he ground and the other at the height of 4th floor...we just need to repeat it until one of the two bulbs breaks or we reach at the 99th floor and test the same... But in case you want to use all the 20 bulbs...you need more resources to test... >given 20 "destructable" light bulbs(which breaks at certain >height), and a building with 100 floors, how do you determine >the height that the light bulb breaks. Ha! You ALL failed. This wasn't an interview question to think outside the box. It wasn't a complicated math question, it was a SPELLING test. You failed. "destructable" is spelled destructible. And those of you that used "destructable" in your posts? You're fired.... I agree with Jose, the same answer is mine The question doesn't say you have to drop them. I would place them inside a pressurized container and take them all the way up to the 100th floor and get the full $20k :) I used to work in a 110 story building. If you handed me a box of lightbulbs and told me to toss them off the roof, I'd call Security on you and keep the lightbulbs. End of story. The true maximum bonus acquirable is $19,000, for you would understand that the bulb will break at some floor above floor one, otherwise the question itself would be insensible to ask. with this being said, starting at floor one (for assurance), drop a bulb. if the bulb breaks, you have your answer, and a nice $19,000 bonus. if the bulb survives, you simply drop the bulb from a higher point, i.e. the next floor up. you repeat this process until you find which floor the bulb breaks, since it will break at some height above the ground. all that mumbo jumbo about an algorithm from a person with a masters in mathematics is complete garbage. very simple question with a very simple answer, -Andrew Romero, ChE Major, Junior, University of South Florida. Go Bulls! This question catches people who are not wired to pick up on details and who also make assumptions or jump to conclusions quickly. I was a licensed EMT-SS in college and similar questions were notorious for being on patient assessment exams. If is fundamental to a full assessment to observer everything and assume nothing. Read the problem carefully and don't make any assumptions, ""given 20 'destructable' light bulbs(which breaks at certain height), and a building with 100 floors, how do you determine the height that the light bulb breaks." Premise: Light bulbs are air tight and are filled with an inert gas or evacuated to prevent oxidation of the filament. Inferences: 1. The problem to solve is "HOW DO YOU DETERMINE the height that the light bulb breaks." 2. The solution to the problem is a "method" (eg. How?) and not "a quantity of units." 3. The light bulbs break "at certain height" which is a single height and not at any or many heights. 4. The problem to solve has nothing to do with the 100 foot building. It could be a resource that could be used to help solve the answer but it is not a variable of the problem. Solutions 1. Light bulbs will break when the difference between their internal and external air pressures exceeds the tolerance of the glass globe of the light bulb. Higher or lower elevations have lower and higher air/barometric pressures, respectively. Therefore, raising or lowering an object changes it ambient air pressure. Hence, the solution is to raise or lower a light bulb until the differences in the internal and external air pressures exceed the tolerance of the light bulb and it breaks. Comments 1. The problem to solve is NOT "determine the height that the bulb breaks when dropped." If it was the answer would be "the ground" because the bulb would break when it hits the ground, not where it is let go to drop. 2. The problem to solve is NOT "determine the height that dropping a light bulb from will cause it to break." NOTE: There are now several versions of this question being asked. It only takes one or two words to completely change the problem and answer. The very point of many questions is not test for higher reasoning and problem solving skills but rather to see how carefully you read the question and how easily you make assumptions or jump to unfounded conclusions. It is the profession of testing groups and HR professionals to keep these test effective. Be aware that the easiest questions to cause someone to slip up on are the most common questions that have been slightly changed. A few years ago I had to hire twelve document reviewers in a week and used a group format in our conference room for the first interview and to test a theory I had. I gave each group a short multiple choice assessment test and instructed them to read the instructions and questions very carefully. The instructions at the very top of the first page were, "Read each question carefully and select the correct choice to not pass this test. Do answer the odd questions all option 'a' and leave the even questions unanswered." It took three groups before anyone followed the instructions. We didn't eliminate anyone over this, but we now use it regularly as a training tool to drive home the importance the details and not making assumptions when reviewing legal documents. Show More Responses the statements says the bulbs break at a certain HEIGHT - then why not just take a bulb and start walking up and see at what floor/height the bulb breaks ..... Go up in 1/5th intervals to the the top Wouldn’t you just contact the lightbulb manufacturer if this was important information to consider? The bigger issue is not breaking the lightbulbs because that’s not what they’re designed to do. The goal is to receive 100% of the bonus without damaging any of the lightbulbs. |
Linux Kernel Engineering at Google was asked...
You have 25 horses, what is the minimum number of races you can find the top 3. In one race you can race 5 horses, and you don't have a timer. 32 AnswersI don't know, but Google it, you'll find the answer. Once you know it, it's obvious. 12 Probably 8. First answer: at least 5 (you have to look at every horse). Second answer: 11. You can race five horses, replace 4th and 5th place horse by two horses from pool of horses that haven't raced, and continue doing this until all horses have raced. Since there are 25 horses, you need 1 race for the first five horses and 10 to go through the remaining 20. Third answer: 8. Round 1 (5 heats) : Race horses in heats of five. Eliminate all 4th and 5th place horses. (15 horses left) Round 2 (1 heat): Race winning horses from every heat. Eliminate 2nd and third place horses that lost to horses in round 2 that came third or worse. (7 horses left). Round 3 (1 heat): Pick any five horses. Race them. Eliminate bottom two and replace with remaining two horses. (5 horses left) Round 4 (1 heat): Eliminate bottom two. Note: after round 2 it may be possible to use some interesting decision tree mechanism to determine the three fastest horses using fewer horses per heat but you still need two heats to do that. This problem assumes horses don't get tired, no ties are possible and a horse's speed is deterministic race after race after race. Good assumptions for brain teasers, but not for real life. Show More Responses Actually, should be 7. Forgot that after round 2 you can eliminate one more horse leaving you with 6 horses, one of which (the winner of the second round), is the fastest horse of them all. One more race with the five horses not No.1 and you pick the top two. 6. First round consists of 5 races of 5 horses. Pull aside the winner of each race in the first round for the final heat and eliminate the bottom 2. 8. Run 5 races of 5 horses. (5) Put all the 3rd place horses in a race, winner is 3rd fastest. (6) Put all the 2nd place horses in a race, winner is 2nd fastest. (7) Put all the first place horses in a race, winner is fastest. (8) The third place horse was beaten by one of the 2nd place horses. So third stays in third. Same for the second place horse. chzwiz, r u sure u r not high? B, what happened in round 2? why 8 horses suddenly get eliminated by 1 race? again, do u know what you are smoking? oh, forget J,..... just speachless 7. chzwiz, your answer is incorrect. One of the first or second place horses could be 2nd fastest and/or 3rd fastest. I drew a grid to visualize the problem. First, run five races to establish 5 groups of internally ranked horses, and you can of course immediately eliminate 4 & 5 of each race. 1 2 3 x x 1 2 3 x x 1 2 3 x x 1 2 3 x x Then race 1st place horses, eliminate 4 & 5, and those they beat earlier. You can also eliminate the horses #3 beat, and the 3rd place horse from #2's first race. 1 ? ? X X 2 ? X X X 3 X X X X X X X X X X X X X X You know #1 is fastest. Race the remaining horses (2, 3 and ?'s), and the top two are 2nd and 3rd. After reading the above answers, this is the same as B's revised answer, but I found it easier to explain/visualize with the grid. @brad ... but isnt dat v dont have timer to know d ranking ... or my assumption is wrong?? I thought v know only 1 result of every race .. i.e. top 1 Spawn, it's true that you don't know timings, but you do know RANKINGS. I don't see errors in logic with each answer above. They may claim to discover the answer with fewer races, but they have too many assumptions or errors to be correct. To do this optimally and without any potential error, you must eliminate as many correctly placed horses as possible and eliminate the maximum number of non-win/place/show horses each round. Round 1: (Races 1-5) You must start with 5 heats @ 5 horses apiece. The non-Win/Place/Show horses of each round have been eliminated, leaving 15 horses. Round 2: (Race 6) You then race the top finishing horses against one another, leaving you with your overall fastest horse. We now have the Win horse, leaving only Place and Show as unknowns. This also eliminates the bottom two horses, leaving 2 horses from this race. There are also only two more unknown horses. Race 7) You may race the Place horses against one another. Only two survive this race, since we know that each of these horses can place 2nd at best. This leaves 2 horses from this race. (Race 8) You may also race the show horses of each round. Since they each have been beaten by two other horses in Round 1, only the 1st place horse of this round survives as the potentially 3rd best horse. This will leave 1 horse in this race to battle for the 2 remaining spots. Round 2 leaves 2 Horses (Race 6) + 2 Horses (Race 7) + 1 Horse (Race 8) = 5 Horses, for 2 unknown spots. Round 3: (Race 9) We can now have the final 5 horses race for the remaining two spots leaving us with the undisputed 2nd and 3rd places. Here is a more complex scenario below in which the top 2 horses come from the same original race and the later races are full of lame horses. Many of the solutions above do not address those problems. Each # is a horse, named by it's inherent ranking. X signifies 'eliminated horse' Race1 R2 R3 R4 R5 1-->R6 3-->R6 11-->R6 16-->R6 21-->R6 2-->R7 7-->R7 12-->R7 17-->R7 22-->R7 4-->R8 8-->R8 13-->R8 18-->R8 23-->R8 5X 9X 14X 19X 24X 6X 10X 15X 20X 25X Round 2: Race 6 (Winners) Race 7 (Places) Race 8 1 -->1st Place 2-->Race 9 4-->Race 9 3 -->Race 9 7-->Race 9 8X 11-->Race 9 12X 13X 16X 17X 18X 21X 22X 23X Round 3: Race 9 2P 3S 4X 7X 11X First Place = 1 Horse -- Race 6 Winner Second Place = 2 Horse -- Race 9 Winner Third Place = 3 Horse -- Race 9 2nd place To fix the formatting issues that appeared as spaces are eliminated above-- Race1________R2___________R3___________R4___________R5____ _1-->R6_______3-->R6_______11-->R6_______16-->R6_______21-->R6 _2-->R7_______7-->R7_______12-->R7_______17-->R7_______22-->R7 _4-->R8_______8-->R8_______13-->R8_______18-->R8_______23-->R8 _5X__________9X___________14X__________19X___________24X _6X__________10X__________15X__________20X___________25X Round 2: Race 6 (Winners)__________Race 7 (Places)__________ Race 8 1 -->1st Place_____________2-->Race 9______________4-->Race 9 3 -->Race 9_______________7-->Race 9 _____________ 8X 11-->Race 9______________12X____________________13X 16X_____________________17X____________________18X 21X_____________________22X____________________23X Round 3: Race 9 2P 3S 4X 7X 11X Less ascetically pleasing than the original, but it will suffice. Show More Responses This problem can be reduced to (viewed as) multiway mergesort: 1) split the horses into groups of five as if we had five files to sort 2) do a multiway mergesort but instead of sorting all horses, stop as soon as you get the top 3 We need one race per group to sort them (5 races total). And 3 more races to get the top 3. We will need 8 races. The interviewer might have been looking whether an applicant was able to spot this relation to algorithms or not. But if this was a brain teaser instead, maybe the answer is less than 8. The answer is definitely 7, here is a fantastic explanation: http://www.programmerinterview.com/index.php/puzzles/25-horses-3-fastest-5-races-puzzle/ Randomly race the horses 5 times and keep a winner's bracket. The 6th race will determine the fastest horse. This is trivial. The 2nd and 3rd fastest could be in the winner's bracket or they could be the 2nd or even 3rd fastest in one of the losing brackets. Then we have to race 2nd and 3rd place from the winners bracket as well as from each original bracket, which had 5. This means we have 12 horses to try. Randomly keep 2 horses out and race 5v5. Keep the top two horses from both. We have 6 horses now. Race 3v3 and keep the top two, leaving 4 horses. Then race these. I count 11? Brute force divide and conquer solution = 18 races. Just be aware of the brute force solution in case there's restriction where we can't use the memory to save the first 3 places. Those who want a system that averages that fastest solving time, the answer will be 7 races.. Those gamblers who want an algorithm that gives the fastest possible solving time (all though sometimes it WILL take longer) the answer is 6. Race 1-5: First 5 races of five.. We randomly seed with no overlaps.. we use this to eliminate the bottom two from each race. I am going to use a two digit number labeling system where the first digit is which race in heat one they competed in and the second digit is which place they obtained in that heat.. These are the horses we have left: 11 12 13 21 22 23 31 32 33 41 42 43 51 52 53 Race 6: We have the winners from each heat compete, and for ease of explanation lets say that they ranked 11, 21, 31, 41, 51.. Now we know that 41, 51 and all the horses slower than them (their heats) are out.. also, we know that any horse slower than 31 is out (ie. 32 & 33), and we know that any horse that is at least two horses slower than 21 is out (ie 23). This leaves 11, 12, 13, 21, 22, 31.. 6 horses. Possible rankings: 11 12 13 21 22 23 31 32 33 Race 7 Rank 1 is already known.. and we just need to know how to organize 12, 13, 21, 22, and 31.. And look at that!! that's 5 horses! We race those 5 and the top two receive the overall rank of 2nd and 3rd. 5 races in round one, 1 race in round 2, 1 race in round 3.. it took us 7 races.. Option two: 6 Races Now, an alternate answer.. when we read "What is the minimum number of races to find the top 3 horses" we can interpret that maybe they don't care about this method working every time.. instead they want to hit up the Vegas Casinos and test their luck, and maybe save some track time.. If i was a gambling man.. i would race the first group of those that i thought looked the strongest.. I would eliminate 2 in that race (we are now down to 23 horses).. and then race the 3rd fastest multiple times and hope that he gets first in the remaining races, thus eliminating 4 horses each time. This is going to be painful for the horse that placed 3rd in heat one. Race 1: Eliminate 2, 23 horses remaining Race 2.. Eliminate 4, 19 horses remaining Race 3.. 15 horses Race 4.. Eliminate 4, 11 horses Race 5.. Eliminate 4, 7 horses Race 6.. Eliminate 4, 3 horses.. The original top 3 from Race 1. So using method 2, we completed this race in 6 races instead of 7! I messed up the possible ranks after race 6.. That should have read.. 11 12 13 11 12 21 11 21 22 11 21 31 Please forgive me. Brad's explanation is the perfect one. All other explanations are junk and impossible to read and follow. Round1: (5 groups) remaining horse 15 Round: (1 groups). Topper from each heat Round: (1 gounds). Forget about the 4th and 5th Heat horses (becoz their toppers are at last place) go to the 3rd position 6 races as the 25 horses are divided into 5 groups each grouping 5 horses in each group , then the winner from each group would be 5 then there should be last n final race to find the first , second and third placed horse . in this way we can find our top 3 horses :) It should be 11. In each race you can only eliminate 4th and 5th place simply because there's a chance that the top 3 in that single heat are the 3 fastest of all the horses. So each race you can select 5 random horses each race or keep the top three in the following race, the outcome is the same. Show More Responses I get 8 races to guarantee you get the top three. 5 races of 5 to get the fastest horse from each group. 1 race to determine the fastest overall. The second fastest horse can be in the group (x) that produced the fastest, 1 race with the remaining 4 fastest from the other groups and the second fastest from group x. That race will produce the second fastest overall guaranteed. 1 more race with the 3 or 4 from the original winners and the replacement from the group that produced the second place horse. That makes 8 races. I dont get it.. It shoudl be five races right? U will know how long each horse takes to cover same distance. Pick the three that took shortest. Y need more rounds? If u down vote my answer, u have the obligation to explain why 😜 Answer is 6. You will have 5 races and 5 winners. Next race with 5 winners is the 6th race and you get top 3. You're welcome. It would be 7, mainly because since there only 5 racers each round, then it would be tournament style. As you can tell, tournament style never determines the rankings in the short term. (Imagine if a new tennis player played against Roger Federer and he loses. He's not bad, he's just really unlucky haha) So in order to determine the answer, you would have to use massive logic and reasoning. First step is obvious: you get 5 sets of horses to race through 5 races. So the number is already at 5. We get the top horse in each one and note them. However, one problem is that you have to consider if fastest horses could lie all in the first, second, third, fourth, or fifth group. But we can't determine that yet, so let's race one more time with the winners of each race. Second step: Race with each winner from their groups. That makes 6 total races so far. Ok, now we can get somewhere with this. So now, its a question of which horses we can eliminate to determine the next race. Who can we eliminate though? Well, we can get rid of: - All the horses in the group with the last race that were 4th and 5th place. This makes sense since if the winner of their groups only made 4th and 5th place in the tournament style race, then they are definitely not the fastest horses. 15 horses remaining. - Well, we can also get rid of the last two horses of each group since we are only looking for the top 3. 9 horses remaining. - We also can get rid of the first place winner since we already know he is definitely the best. 8 horses remaining. - Since we already determined who the fastest horse is, now we have to determine who the second and third fastest horse can be. In that case, the second place horse from the last round can get rid of the third horse of that group, since he definitely has no shot of being the first or second fastest horse of this new race. Also, in the third group, we can get rid of the second and third horse in the group due to the same reasoning above. 5 horses remaining. Oh wow! We now have 5 horses left! This means we can just have a clean race and find the second and third fastest horse. So overall, the answer is 7 races! In my opinion, you need 26 RACES to make sure that you get the top 3 without a timer. You need to know that without a timer if we plan only 5 races with 5 horses on each one, the last horse on the first group could end the race in 1 minute while the first horse on the second group (the winner) could end it in 2 minutes, which mean that the last horse of the first group is much faster than the first horse of the second group..and this is why we need to make a total of 26 RACES to determine the top 3 as follow: 5 RACES with 5 horses each .> We get the 5 winners from each race .> We race the 5 winners > We get the top 4 > We race the top 4 with one of the remaining 20 horses > we get the top 4 > we race the top 4 with one of the remaining 19 horses > we get the top 4 > we race the top 4 with one of the remaining 18 horses...etc until the last race then we select the top 3 winners from the last race. 5 RACES + 1 RACE + 20 RACES = 26 RACES HERE IS THE METHOD FOR THE MAXIMUM RACES😂😂 5 races 5 horses in a race, then repeat so you have a larger pool of data and more accuracy. Then take all the 1 and 2nd place winners that changed horses and run them 1 on 1 which ever wins takes the spot (0-20 races), so now you have 10 horses left. Split them into 2 groups and race each group twice repeating the 1 on 1 method using the first and second place horses, now you have 4 horses race them all in one race, run it twice again doing the 1 on 1 method. So that totals to 31 races...I think...also would be about time to retire these horses after 31 races LOL Shoot 36 races not 31 5 races - place all the 25 scores in a chart and pick top 3. No more races are needed. One or more comments have been removed. |
How many different ways can you get water from a lake at the foot of a mountain, up to the top of the mountain? 28 AnswersYou don't really need to worry about it, because nature does it anyway. When water in the lake evaporates into the air, it forms cloud, then rains... yeah you know the story. Pumpit, carry it, by will of God. The easiest way would be to just pump it, but the variable costs of that can add up quickly over the long-term. The cheapest way I can think of is to create some sort of a siphon that runs from the lake, over the top of the mountain, and back down to a different spot that's lower than the lake. If you set it up right, you could drain a small amount of water at the mountain top and the siphon would still work. Show More Responses Jesus guys. You're interviewing for DISNEY! Use some imagination. My favorite so far is people power. Set up a huge rotating conveyor belt with small buckets on it, that dip into the lake. A person hops on at the top, and rides it down. This would be great if all the jobs were at the bottom, or if they needed t odo something else at the bottom. It would be fun too! Other ways might be to boil it yourself! dig under a section of lake and start a huge fire with a big condenser tube over it. Have the tube curly cue all the way to the top of the mountain, condense up there, then drip out as nice cool, distilled water. Use your imagination. Be creative. None of you would have been hired for this job. It's Disney... CGI effects! The water doesn't really get there, it just looks amazing to the public. The three basic ways are as follows 1. Pull it up with suction, if the mountain isn't too high 2. Pump it up from the bottom 3. Carry it up But the number of ways to implement these three basic methods is unlimited. Grab those buckets. Miss Disney is at it again.... Me: There are just too many ways to count, but If I were on the project, it would be the first one on my list that works. Two. The future Project Engineering Intern delegates project to Mickey, Minnie and Donald, who team up with IT and the Web departments to source their top talent. The end result: the SME's create an amazing interactive solution engaging the end user to figure out different options. Kudos for the special effects guys, says the Project Engineering Intern, who decided to work smarter not harder. He spent his time gaining valuable experience at Disney. The interviewer is now a Disney alumni as a result of asking vague interview questions. If you really think about it, the possibilities are endless. Start a fire, the forest service will do it for you. Id say off the top of my head around 9 million, but my favorite method would be to freeze it, take a third of the water on a one way jet to Agrabad and on the way, over the summit, drop off the load and that pesky tucan Gilbert Godfrey. Another third goes right into the cannon. The final third is cut in two, the first half is made into sno-cones and distributed to children going to the top of the mountain to see the Lion King exhibit on the ski lift, the remaining ice is placed in 8 oz. blue mason jars and hand carried by the seven dwarves second cousins (on the maternal side). I would borrow the sorcerer's hat, find all the brooms he left laying around and reanimate them to carry buckets of water up the mountain. It would be magical! Show More Responses Tell all the Disney cast members that there is a kegger at the top of the mountain, but the cover charge is a bucket of water from the lake. Depends >>> '37'*37 '37373737373737373737373737373737373737373737373737373737373737373737373737' >>> 37*37 1369 And finally 37*37 can be solved easily as 37*37=(3*3)*100+(7*3+7*3)*10+7*7 Water can be in three forms, liquid, gas (vapor) or solid (ice). Any number of ways for each form as can be devised, but basic answer is 3 ways, in liquid form, in vapor form or in solid form. The question was "how many different ways", not how. The answer is 1. You could get a mouthful of water and then hike up the mountain and spit it out. You could drink as much water as you could and then hike up the mountain. You'd be sweating a lot by the time you got there and you'd probably need to pee by then. I like altaholic's idea. You could always set up a fan that blows air into a tube which contains water from the lake and then blows the moist air to the top of the mountain. Combine that with Lex's idea of condensing it at the top of the mountain. I liked Lex's other idea of the conveyor belt. You could throw rocks down the conveyor belt and use the power generated to pull the water to the top. Over time the mountain would get shorter and you wouldn't have to move either rocks or water as far. thru motor pump or thru carryng with bucket there are two ways to do that.. one is pumping it. the other is carrying with the bucket.. The water is coming from the top of the mountain, therefore the water source that feeds the mountain top water will replenish itself. Infinite. This may take a bit of time but, construct pools and rain catches at the top of the mountain. With adjustable dam like controls throughout the length of the downward grades. Using progressively small return piping to send the water back up the mountain and smaller pumps also allow for two pools (to be had at both top and bottom) to look like a self sustaining hourglass. Also the pumps and dam controls could be hydroelectric sooo that's a load off your power bill. Show More Responses Infinite! 1) Pump It 2) Use an Elevator Rally system by allowing gravity to control the buckets of water as the travel to the top, empty, then fall back down. 3) Carry it infinitely wo water evaporates, turns clouds and rain in the mountain |
The first question he gave me was not hard. 1. You call to someone's house and asked if they have two children. The answer happens to be yes. Then you ask if one of their children is a boy. The answer happens to be yes again. What's the probability that the second child is a boy? 2. (Much harder) You call to someone's house and asked if they have two children. The answer happens to be yes. Then you ask if one of their children's name a William. The answer happens to be yes again.(We assume William is a boy's name, and that it's possible that both children are Williams) What's the probability that the second child is a boy? 12 Answersthe second ans should be 1/3 Actually the asnwer is 3/4. Lets go through the conditional probabilities. If the first child is named William and the second is NOT: the prob. of the second child being a boy is 1/2. If the second child is named William and the first is NOT: the prob. of the second child being a boy is 1. If both children are named William: the prob. of the second child being a boy is 1. Now, assuming equal probs. of the first, second, or both children being named William, the total probability of the second child being a boy is (1/3)(1/2)+(1/3)(1)+(1/3)(1)= 5/6 ^^^^^^^^^^^^^ Correction... I meant to write the answer is 5/6 Show More Responses You're both incorrect. The first answer is 2/3 and the second answer is 4/5. Let B stand for boy (not named William), Bw be a boy named William, and G be a girl. 1. The sample space is: (B,B) (B,G) (G,B) It's easy to see that two of these cases have a boy as the second child so the probability is 2/3. 2. The sample space is: (Bw, Bw) (Bw, G) (G, Bw) (Bw, B) (B, Bw) 4 of the 5 cases have a boy as the second child, and therefore the probability is 4/5. The first answer is 2/3, as mentioned. But the second question hasn't been answered correctly here. Given a person X, define e = P[X's name = William | X = boy]. Then, note that P[X's name = William] = P[X's name = William | X = boy] * P[X = boy] = e / 2 (the problem states that William is a boy's name). Letting C1 be child 1 and C2 be child 2, we are asked to find P[C2 = boy | Y], where for notational simplicity, Y denotes the event "C1's name = William or C2's name = William." By Bayes' rule, we have: P[C2 = boy | Y] = P[C2 = boy, Y] / P[Y] == Denominator: P[Y] = 1 - P[C1's name != William AND C2's name != William] = 1 - e/2 * e/2 = 1 - e^2/4. == == Numerator: P[C2 = boy, Y] = P[Y | C2 = boy] * P[C2 = boy] = 1/2 * P[Y | C2 = boy] = 1/2 * P[C1's name = William or C2's name = William | C2 = boy]. To compute P[C1's name = William or C2's name = William | C2 = boy], there are 3 cases. Case 1: C1's name is William, C2's name isn't William (given C2 is a boy). This is e/2 * (1- e). Case 2: C2's name is William, C1's name isn't William (given C2 is a boy). This is e * (1 - e/2). Case 3: both names are William (given C2 is a boy). This is e/2 * e. Summing these 3 cases gives e/2 - e^2/2 + e - e^2/2 + e^2 / 2 = 3e/2 - e^2/2, which is the numerator. == Dividing, we have (3e/2 - e^2/2) / (1 - e^2/4) = e * (3 - e) / (4 - e^2). As a sanity check, note that setting e = 1 implies that all boys are named William, and our probability is 2/3, as in the first question. Setting e = 0 implies that no boys are named William, in which case our probability is 0. unless William's prior distribution is provided. The only information we got is that William is a boy name. Thus the event is equal to at least one of them is a boy = 2/3. Becareful when you guys calculate probability with outcomes UNEQUAL LIKELY. 1. BB, BG, GB, GG 1/4 each, which later reduced to only BB, BG, GB with 1/3 probability each. So the probability of BB is 1/3 2. Let w is the probability of the name William. Probability to have at least one William in the family for BB is 2w-w^2, For BG - w, GB - w, GG - 0. So the probability of BB with at least one William is (2w-w^2)/(2w+2w-w^2) ~ 1/2 1. P[C2 = boy | C1 = boy ] = 0.5 since these are independent events 2. P[C2 = boy | C1 = boy and is called William ] = 0.5 since these are independent events The answer by Anonymous poster on Sep 28, 2014 gets closest to the answer. However, I think the calculation P[Y] = 1 - P[C1's name != William AND C2's name != William] should result in 1 - (1- e /2) ( 1- e / 2) = e - (e ^ 2 ) / 4, as opposed to poster's answer 1 - (e^2) / 4, which I think overstates the probability of Y. For e.g. let's assume that e (Probability [X is William | X is boy]) is 0.5, meaning half of all boys are named William. e - (e ^ 2) / 4 results in probability of P(Y) = 7/16; Y = C1 is William or C2 is William 1 - (e ^ 2) / 4 results in probability of P(Y) = 15/16, which is way too high; because there is more than one case possible in which we both C1 and C2 are not Williams, for e.g. if both are girls or both are boys but not named William etc) So in that case the final answer becomes: (3e/2 - (e^2)/2) * 0.5 / (e - (e ^ 2) / 4) = 3e - e^2 / 4e - e^2 = (3 - e) / (4 - e) One reason why I thought this might be incorrect was that setting e = 0, does not result in P(C2 = Boy | Y) as 0 like Anyoymous's poster does. However I think e = 0 is violates the question's assumptions. If e = 0, it means no boy is named William but question also says that William is a Boy's name. So that means there can be no person in the world named William, but then how did question come up with a person named William! I think second child refers the other child (the one not on the phone) In this case answer to first is 1/3 and second is (1-p)/(2-p) where p is total probability of the name William. For sanity check if all boys are named William the answers coincide. i think you guys are doing way too much and this is a trick question, these are completely independent events, i could name my child william, i could name it lollipop - the chances of it being a boy are still .5, regardless of its brothers name as well . (im going with .5 for both questions) keep in mind this is a quick phone interview question so they wont give anything thats too calculation heavy, involving e^2 exponents fractions etc, because you're supposed to be able to do it in your head Answer by indosaurabh is correct, i go to harvard |
Implement a power function to raise a double to an int power, including negative powers. 11 AnswersCould be implemented many ways. I got the feeling that the interviewer wanted to see you approach the problem in multiple ways and demonstrate confidence in your math and recursive skills. #include #include #define MAX_ARRAY_LENGTH 256 double power(double, unsigned int); int main(int argc, char** argv) { double a = atof(argv[1]); int b = atoi(argv[2]); double result = power(a, b >> 31 == 0 ? b : -b); if ((unsigned int) b >> 31 == 1) { result = 1 / result; } printf("%f\n", result); return 0; } double power(double a, unsigned int b) { switch (b) { case 0: return 1.0; case 1: return a; default: return (b & 1) == 0 ? power(a * a, b >> 1) : power(a * a, b >> 1) * a; } } c implementation of the above (no recursion): int ipow(int base, int exp){ int result = 1; while(exp){ if(exp & 1) { result *= exp; } exp >>= 1; base *= base; } return result; } Show More Responses int power(double n, int exp) { bool npower = (exp < 0) ? true : false; double result = 1; exp = abs(exp); // get the absolute value for (int i = 0; i < exp; i++) { if (npower) { result = result/n; } else { result = result*n; } } return result; } C# code verified: static double Power(double d, int exp) { if (d == 0 || exp == 0) { if (exp >= 0) { return 1; } else { return double.PositiveInfinity; } } int expAbs = Math.Abs(exp); double res = d; for (int i = 1; i 0) ? (res) : (1 / res); } double power(double x, int y) { if(y == 0) return 1; int sign = 1; if(y < 0) sign = -1; y = abs(y); double d = power(x, y/2); if(y%2 == 0) d = d*d; else d = x*d*d; if(sign == -1) return 1.0/d; else return d; } I am surprised that not a single person here had noticed that the guy asked to raise a DOUBLE to a given power. Men, double are not integers. Their exponent is stored in a part of their binary representation. If you multiply n times a double you will make n times a rounding error and n useless calculations. Just changed the binary part of the double that is related to its exponent, and here it is, your double has been raised to a given power, a you absolutely lost no precision, and you've made 0 calculations. This is basic stuff, every university teaches that to its students... floating numbers representation... I believe interviewer is expecting for this public static double Power(double x, int y) { double result = 1; bool isNegative = y 0) { if ((y & 1) > 0) { result *= x; } y = (y >> 1); x *= x; } if (isNegative) result = 1 / result; return result; } Verified C# static double Pow(double b, double exp) { if (exp == 0) return 1; else if (exp > 0) return b * Pow(b, exp - 1); else return 1 / Pow(b, -exp); } Does it get more compact? TD's answer is interesting, but not very useful. If you actually try it you'll find that since the double's base is 2, any changes to the exponent portion approximately multiply (or divide) numbers by a power of two. I say approximately here, since TD forgot to mention that the number itself isn't stored in float point numbers, only the digits after the implied 1. So yes, it's important to know how floating point numbers work, but modifying the exponent portion of a floating point number is a fundamentally incorrect solution. public double power(double num, int exp) { if(exp == 0) return 1; double res = 1; for(int e=Math.abs(exp);e>0;num*=num,e>>=1) { if( (e&1) == 1) res *= num; } return (exp>0)?res:1.0/res; } |
Implement division without using multiplication or division. It should work most efficient and fast. 11 Answersexp(ln(a)-ln(b))=a/b What if one or both of a,b is less than zero. ln(x) for x < 0 is not defined. we can use bit shift operator. e.g. 4 is 100 in binary we want to divide 4 by 2 so right shift 4 by 1 bit 4>>1, so we get 010 which is 2. Show More Responses This solution rounds down to the nearest signed integer // Implement division without using multiplication or division. It should work most efficient and fast. int Divide(int divisor, int dividend) { int divisionCount; int tmp = dividend; if (tmp - divisor > 0) { tmp = tmp - divisor; divisionCount++; } // This will apply the correct sign to the quotient if ((divisor & 8) ^ (dividend & 8) != 0) { divisionCount = divisionCount | 8; } return divisionCount; } // correcting previous answer int Divide(int divisor, int dividend) { int divisionCount; int tmp = dividend; if (tmp - divisor > 0) { tmp = tmp - divisor; divisionCount++; } // This will apply the correct sign to the quotient if ((divisor & 0x80000000) ^ (dividend & 0x80000000) != 0) { divisionCount = divisionCount | 80000000; } return divisionCount; } can anyone post solution in java? public class Solution { public static void main(String[] args){ int top=32; int bottom=4; int count=0; boolean negative=(top*bottom)=bottom){ top=top-bottom; count++; } System.out.print((negative)?"-":""+String.valueOf(count)+"..."+top); } } Obviously the interviewer would not allow us to use Math functions like exp, log etc. We are supposed to use the Long division method or the Newton Raphson method to find the quotient. Newton Raphson is the fastest but uses operator * (multiplication) though. http://stackoverflow.com/a/5284915 Python version that gives you an idea how it works: i = 0 while divisor = 0: if dividend >= divisor: dividend -= divisor result |= 1 >= 1 i-=1 plus some code to check for 0 and support negative values #Write a program to do division without division or multiplication 2 3 def division(dividend, divisor_initial): 4 divisor_final = divisor_initial 5 quotient = 1 6 while dividend - divisor_final > divisor_initial: 7 quotient += 1 8 divisor_final = divisor_final + divisor_initial 9 number = divisor_final - divisor_initial 10 remainder = dividend - divisor_final 11 return quotient,remainder 12 13 14 def main(): 15 print division( 101, 3) 16 17 18 if __name__ == "__main__": 19 main() |
You are given an array with n positive integers where all values in the array are repeated except for one. Return the one that is not repeated. 13 Answerspublic static int notRepeated(int[] given) { Map m = new HashMap(); for(i=0; i < given.length; i++) { if(m.get(given[i])) { m.put(given[i], 2); } else m.put(given[i], 1); for(x:m) { if(x == 1) return x; } } } If you have an array of positive integers with only ONE non repeated integer, the easiest thing is just xor them all. Whatever you return will be the answer. Perl answer below sub findNotRepeated{ my ($arr) = @_; if(@$arr==0) { return - 1; } my $val = 0; foreach(@$arr) { $val ^= $_; } return($val); } sub findMissingElement{ my ($arr,$arr2) = @_; if(@$arr==0 || @$arr2 == 0 ) { print " arr2=" .@$arr2 . "X\n";; return - 1; } my $val = 0; foreach((@$arr , @$arr2)) { $val ^= $_; } return($val); } first sort the array.n then 1)for i=1 to n { if ( element [i] !=element [i+1] ) { cout< Show More Responses This answer is in-place with O(n) complexity. A slight improvement over the space complexity of the Hash Map answer. public int returnNonRepeat(int[] input) { if(input.length < 3) return -1; else { int repeat = null; if(input[0] == input[1]) repeat = input[0]; else if(input[0] == input[2]) return input[1]; else return input[0]; for(int i = 2; i Cant use XOR as it fails when any element repeats odd number of times..... Can use hash map with O(n) time and O(n) space only 2 possible solutions 1.) using sorting 2.) using additional space. which will be less than o(n) sub find_odd { my @a = @{$_[0]}; my ($i, $n); $n = $a[0]; for $i (1 .. $#a) { $n = $n ^ $a[$i]; } printf("number is %s\n", $n); } Use xor public static int NotRepeated (int ar[], int n) { int answer = -1; ArrayList arList = new ArrayList(); System.out.println(Arrays.toString(ar)); int n1 = 0; int n2 = 1; for (int i = 0; i < n; i++) { n1 = i; n2 = i +1; if (i == ar.length && (ar[i] != ar[i-1])) answer = ar[i]; else if (ar[n1] == ar[n2]) i++; else if (ar[0] != ar[1]) answer = ar[0]; else { if (ar[n1-1] == ar[n1]) { if (ar[n2] == ar[n2+1]) i++; else answer = ar[n2]; } else answer = ar[n1]; } } One or more comments have been removed. |
See Interview Questions for Similar Jobs
- Mechanical Engineer
- Intern
- Engineering Intern
- Engineer
- Engineering
- Mechanical Design Engineer
- Mechanical Engineering
- Software Engineer
- Design Engineer
- Manufacturing Engineer
- Product Design Engineer
- Mechanical Engineer I
- Senior Mechanical Engineer
- Process Engineer