Intern Interview Questions in United States
intern interview questions shared by candidates
Top Interview Questions
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? 60 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^. 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? 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. 2 as many have indicated above. The 3 is the kneejerk reaction but 2 is the correct answer. Marty's answer is correct, but he does not explain why. The logic of the balance scale is three-valued: . Its most efficient use is the recursive application of the three-valued logic until there is only one item left. The integral ceiling of ln(x)/ln(3) thus gives the fewest number of times you have to use the balance scale to find the uniquely heaviest ball of x balls. Ceiling(ln(8)/ln(3)) = 2. TvRef Reviewing the answers from over the years has been fun! Some time I would like to be the interviewer to ask these kinds of questions. In first looking at the question, I thought, "probably eliminate as many as possible with the 4 and 4" but then why would it he a thought experiment, less one in an interview, if it was so 2 dimensional? Whether or not getting to the best answer is much of the point, being reductionist by ignoring details, like the context of who is asking, lead me to go my own way as of the question was just text on a screen. There's a lot of 3 dimensional information you could get from someone by this question -- how nervous they are, if they don't then you see how they handle that, or how much they think of their answers to anything. I wonder, were the semantic holes in the question also intentional? In the comments people have written about technicalities -- things about how it wasn't specified that they were only visually identical, and therefore the question is contradictory. Or, how it didn't explicitly specify how to consistently, by most likely repeated efficient scenario, find the heavier ball, so people started that the least possible would be 1 if lucky. Then, since it wasn't explicit that you have to know which one was heavier, people said you could go 0 and guess the right one without the scale, either by direct guessing or trusting your hands with an unspecified sized difference in weight. If the word choice is designed to allow for those, perhaps the question is even more fun than I thought. One could see where and if one goes or gets hung up, see if one would ask clarification if they got hung up, or claim steadfastly about their thoughts being the most important on it, or focus elsewhere -- then that would be another layer to the question that makes it more interesting than I originally thought. I like tea. Show more responses 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 |
Intern at Google was asked...
Find the max value in an array. The array is "semi-sorted". Here is an example: { 1 3 4 7 9 10 12 13 12 6 3 } As you can see, the array increases and then decreases at one point (13). 20 AnswersSimply walk the array to find the max in O(n) time. Compare the current max to the next element all the way until the end of the array. O(logn) approach: int max_value_in_semisorted_array(int* arr, int start, int end) { if (start == end) return arr[start]; int middle = (end + start) / 2; if (arr[middle] > arr[start]) return max_value_in_semisorted_array(arr, middle, end); else return max_value_in_semisorted_array(arr, start, middle); } No, your O(logn)-approach doesn't work. Try this: 1 5 8 10 9 8 7 6 5 4 Show more responses The previous O(log n) approach doesn't handle arrays of odd length. int findPeak(int * array, int start, int end) { if ((start == end) || ((start == (end - 1)) && (array[start] > array[end]))) return array[start]; if ((start == (end - 1)) && (array[start] > array[end])) return array[end]; int middle = floor((start + end) / 2); if (array[middle] > array[start]) return (findPeak(array, middle, end)); else return (findPeak(array, start, middle)); } Remember to include math.h for the floor function. It seems, that it doesn't matter if the array is of odd or even length(btw, my example is not odd :)). This approach doesn't work when the max element is in the first half of your array and the middle element is greater than the first one. We cannot guarantee that if the middle element is greater than the first, our array increases monotonically from x[1] to x[middle] and we should search the max element in the range from middle to end. It is necessary to check two elements on each side of our middle element to find out where the array increases , where decreases, and where the peak is. And only then we can guarantee something about our max. The maximum is obviously just the inflection point in the list... some of the posted solutions here are absurdly complex for this. Brute force solution can be ofcourse O(N). But we can make it better: mid = (start + end )/2 if mid > mid + 1 && mid > mid - 1 return mid else if mid mid -1 search mid -> end else if mid > mid + 1 && mid mid @Mo - This won't be work for an array where the max element is hidden in the first / second half of the main array. Eg: {1,3,9,1,-2,6,2,2,5,-1} In your test case, I see that the numbers increase, decrease, increases, decreases and so on. I thought the question says the list is semi sorted. So my program assumes that the numbers increase and then decrease. We need to find the peak. At least that is my understanding. private static int recFindPeak(int[] a, int start, int end) { if(start == end) return a[start]; int mid = (start+end)/2; if((a[mid] > a[mid+1])&&(a[mid] > a[mid-1])) return a[mid]; else if(a[mid] > a[mid-1]) return recFindPeak(a, mid+1, end); else return recFindPeak(a, start, mid-1); } My codes: int findPeak(vector num) { if (num.empty()) return 0; int lower = 0; int upper = num.size()-1; while (lower num[mid+1]) return num[mid]; else if (num[mid-1] < num[mid] && num[mid] < num[mid+1]) lower = mid+1; else upper = mid-1; } } 1. Walk from begin to mid comparing a[i] a[j] and stop decrementing j when this condition fails. 3. If a[i] < a[j], then return a[j], else return a[i]. Show more responses 1) find the pivot of the highest number of the semi sorted list ,using binary search on the array.(logn) 2) From their do the linear serach for finding max ,also compare with last element of the semi sorted list. strange, some lines missing for above solution: shouldn't be one line : if((end-start)==1 && arr[end] arr[start]) but: if((end-start)==1 && arr[end]<=arr[start]) { return arr[start]; } def maxInSemiSortedArray(inputData): low, high = 0, len(inputData) -1 while(low inputData[mid-1] and inputData[mid] > inputData[mid+1]: return inputData[mid] elif inputData[mid] < inputData[mid+1]: low = mid + 1 else: high = mid -1 def maxInSemiSortedArray(inputData): low, high = 0, len(inputData) -1 while(low inputData[mid-1] and inputData[mid] > inputData[mid+1]: return inputData[mid] elif inputData[mid] < inputData[mid+1]: low = mid + 1 else: high = mid -1 public static Integer getMax(int[] arr){ int max = Integer.MIN_VALUE; int start = 0; int end = arr.length -1; while(start max){ max = arr[mid]; System.out.println("max :"+max); } if( arr[mid+1] > arr[mid]){ start = mid+1; }else if( arr[mid] > arr[mid-1]){ System.out.println("arr[mid]"+arr[mid]+"arr[mid-1] :"+arr[mid-1]); return arr[mid]; } else if(arr[mid] < arr [mid-1]){ end = mid -1; } } System.out.println("Max :"+max); return max; } public static void main(String[] args){ //int[] arr = new int[]{1,3,5,4,2}; int[] arr = new int[]{1,2,4,6,7,8,5,3}; System.out.println("Max is:"+getMax(arr)); } some codes are messed up above. Here is the clean code. public static Integer getMax(int[] arr){ int max = Integer.MIN_VALUE; int start = 0; int end = arr.length -1; while(start max){ max = arr[mid]; System.out.println("max :"+max); } if( arr[mid+1] > arr[mid]){ start = mid+1; }else if( arr[mid] > arr[mid-1]){ System.out.println("arr[mid]"+arr[mid]+"arr[mid-1] :"+arr[mid-1]); return arr[mid]; } else if(arr[mid] < arr [mid-1]){ end = mid -1; } } System.out.println("Max :"+max); return max; } public static void main(String[] args){ //int[] arr = new int[]{1,3,5,4,2}; int[] arr = new int[]{1,2,4,6,7,8,5,3}; System.out.println("Max is:"+getMax(arr)); } One or more comments have been removed. |
Sales Strat Intern at Goldman Sachs was asked...
Suppose we hire you, and you and the rest of the new interns decide to go buy a cup of coffee. Each intern purchases one cup of coffee. One of the interns suggests everyone play a game. Everyone will flip a fair coin, dividing the group of interns into two subgroups: those that got heads and those that got tails. The game is this: whichever group is smaller evenly splits the cost of everyone's cup of coffee (i.e. if there are 5 interns, 3 get H, 2 get T, then the two interns that got tails each buy 2.5 cups of coffee). However, nothing says you need to play this game. You can choose to buy your own cup of coffee and not play the game at all. The question: Should you play this game? (Note: You may assume that there is an odd number of interns, so there are no ties, and that if everyone gets H or everyone gets T, then everyone loses and just buys their own cup of coffee). 18 AnswersHint: Despite its look, this is not a math question. I dont get it, Would you please provide more hints? Assume each coffee costs $1, for simplicity. So this is effectively a choice between two outcomes: paying $1 with probability 100%, or paying $0 with some probability and paying more than $0 with some probability. So you ask yourself: what is your expected cost in the second case? Give that a try and see if you can figure it out. However, I want to remind you that the question is "should you play this game?" The answer to this question isn't just a math question. If you only work out expected values, you've missed the point. For example, a separate question (with the same kind of flavor as the direction I'm trying to lead you) is this: suppose I give you a choice of two outcomes. Either you get $1 with 100% probability or I give you $500,000,000 with probability 1/100,000,000 and 0 otherwise. Which would you pick? Now what if it was the same first choice, but the second choice was $50 with prob 1/10 and 0 otherwise? Now which would you pick? These are the kinds of things you want to think about while answering this kind of question. Let me know if you have anymore questions. And if you want me to post the answer, just let me know. Show more responses I think I get it. It's about investor's risk appetite. Investors is likely to take guaranteed gains, here is $1. Well yes and no. This is indeed a risk aversion question. If you work it out, you'll find that the EV in each case is exactly the same (your EV is -1 cup of coffee in both scenarios) but that's not the end of it. It's also really a question for them to test your risk aversion. You can really support either answer, and *should* comment on the validity of either answer. My answer was to go with buying my own cup of coffee, and followed it up with a story where a friend of mine had tried to get us to play credit card roulette (which is similar in spirit to this game) and I told him that I did, in fact, say no in that instance and why I said no. However, traditionally people are risk-averse when faced with gains and risk-seeking when faced with losses, so many would probably choose to play the game. But this is as much a question about your psychology as it is about your math skills. And that's why this is such an awesome question, and is probably a question that kills most people they ask it to. Would you please explain to me how do you get -1 for the second scenario? There are 50% H and 50% T. Therefore players have 50% opportunity in the winning group. Given 5 interns, there are two combination of lossing group (4 vs. 1 and 3 vs. 2). EV=0.5*0 + 0.5*(0.5*-5 + 0.5*-2.5) = -1.875. The probability of winning isn't 50%. It's actually slightly above 50%, but that's not the way to look at it. The total number of coffees that need to be bought is n, where n is the number of interns. Going into this game, every intern is the same so they each have the same expected value, and the sum of the expected values must equal -n. So everyone has an EV of -1 as claimed. Thank you very much. I finally got it. I'm still not sure why you said no if the EV is the same? It's a matter of risk preference. See the example I gave in my Mar 19 posting: "Suppose I give you a choice of two outcomes. Either you get $1 with 100% probability or I give you $500,000,000 with probability 1/100,000,000 and 0 otherwise. Which would you pick? Now what if it was the same first choice, but the second choice was $50 with prob 1/10 and 0 otherwise? Now which would you pick? These are the kinds of things you want to think about while answering this kind of question." You would probably not play in the first instance and consider possibly playing in the second. (And those instances even have the risky game with a HIGHER EV). This coffee game is the same kind of game, and even if the EV is the same in each case, the volatility is not the same. It is usually a good rule of thumb to take the lower volatility outcome if the EV is the same (think Sharpe Ratio here! Or think efficient frontier here! Both get the point across I think.). Does that help? I say yes. To play the game. Only because I'm prepared if I lost. The fact that I can afford to loose, makes me want to try my chance at wining I would play the game. Consider the expected price with n total interns splitting a total cost of P. That is P/2*E[1/(N)|you're paying]. This is simply equal to P/2*E[1/(N+1)] where n is a binomial now corresponding to n-1 interns. Notice that 1/n+1 is a concave function. That means that P/2*E[1/(N+1)] <= P/2*(1/E[N]+1)=P/2 * 1/( (n-1)/2 + 1)) = P / (n +1). So it pays to play on average Apologies, but both of the above answers are incorrect. The EV of playing is the same as the EV of not playing. Show more responses No way would I play! The most money I save is a dollar the most money I can lose ( in the case of five interns) is 4 dollars... That's a 400 percent downside verse a 100 percent upside ( kind of you cannot technically compute your return on zero dollars invested). Plus, I do not even drink coffee! Stupid...I don't have time to play games at work. The EV in both scenarios are not the same: it's clear when think about the case where there are n = 3 interns. I've already explains why they are the same. In either scenario there will be n cups of coffee bought (3 in your case) so total EV is -n (-3 in your case). In the game each person is the same as any other so their EV must all be the same. That is why in the game the EV is -1 (same as if they buy their own cup of coffee). To argue otherwise is to argue that either the total EV is not the number of coffees purchased or that someone has an unfair advantage in the game. Incidentally, if you are going to claim that someone who has given you the answer is wrong, you should provide more of a response than "go think about it." if v = pay by game -1 . Then all have five intern have same distributed V by symmetry 5EV=0 It's zero sum. |
What was one of your best achievements on a project in the past? 19 AnswersAnswered about a previous internship, mentioned scalability and had a small discussion on that. Were there any coding questions? And was this for an internship? There was a coding question. It was for the SDE summer internship. Show more responses Sorry last question, how long did it take for them to give you a final phone interview. It's been 5 days now for me.should I follow up? From what i've heard and seen, just wait, following up will barely do you any good. Hey, I just have one question out of curiosity, was the second online assessment web-cam proctored? i heard amazon is changing their recruiting process. Many people complained that the online proctoring was an invasion of their privacy. I also had a second online assessment but it was not webcam proctored. I am assuming the recruiting process is now two online non webcam assessments then a final phone interview. My friend had that round of interviews with Amazon 2 weeks ago. if you dont mind, could you tell us the phone interview questions ? Can you describe your phone interview? Do you pick your lang? do they ask you concept questions? do you do a coding problem? etc... No that's cheating Who has their phone interviews soon? I still haven't gotten back with a scheduled phone interview after the second assessment. Anyone else know long the time gap was between the second assessment to final phone interview? I just finished the second online assessment today. Now waiting for their reply. How long did it take for them to get back to you after the second online assessment? It's been almost 2 months and I have not heard back. Show more responses Took about 2 days. If you have a recruiter you should email them over that kind of a length. Anyone hear back? Its been 1 week now and I do not have a recruiter...How are we supposed to contact a recruiter when we do not have one. I just got my first logical question part, it says webcam should be enabled. Is there any place i can practice those from? Did you get the coding question correct for your phone interview? Has anyone gotten an offer or response yet after their phone interview I had mine last Thursday. If you had a phone interview in February and got an offer pls lmk One or more comments have been removed. |
Data Scientist Intern at LinkedIn was asked...
Find the second largest element in a Binary Search Tree 16 Answersfind the right most element. If this is a right node with no children, return its parent. if this is not, return the largest element of its left child. One addition is the situation where the tree has no right branch (root is largest). In this special case, it does not have a parent. So it's better to keep track of parent and current pointers, if different, the original method by the candidate works well, if the same (which means the root situation), find the largest of its left branch. if (root == null || (!root.hasRightChild() ) { return null;} else return findSecondGreatest(root, root.getValue()); value findSecondGreatest(Node curr, value oldValue) { if(curr.hasRightChild()) { return (findSecondGreatest( curr.getRightChild(), curr.value)); } else return oldValue; } Show more responses The above answer is also wrong; Node findSceondLargest(Node root) { // If tree is null or is single node only, return null (no second largest) if (root==null || (root.left==null && root.right==null)) return null; Node parent = null, child = root; // find the right most child while (child.right!=null) { parent = child; child = child.right; } // if the right most child has no left child, then it's parent is second largest if (child.left==null) return parent; // otherwise, return left child's rightmost child as second largest child = child.left; while (child.right!=null) child = child.right; return child; } Soln by "mindpower" works. Thank you. I am trying to solve a similar problem Find the 2nd nearest high(in in-order traversal) value for a given node Eg: Given nums: 12 7 14 3, construct a BST. If the given value is: 7 then we should return 14 (in the sort order: 3, 7, 12, 14) if the given value is: 3 then we should return 12 (in the sort order: 3, 7, 12, 14) Generic solution in C# for any k. Notice that this example can be easily changed to find the k-th smallest node by doing a depth-first recursion on root.Left first, and then a tail recursion on root.Right. public Node GetKthLargest(int k) { return GetKthLargest(ref k, this.Root); } Node GetKthLargest(ref int k, Node root) { if (root == null || k < 1) return null; var node = GetKthLargest(ref k, root.Right); if (node != null) return node; if (--k == 0) return root; return GetKthLargest(ref k, root.Left); } recursion is not needed. SecondLargest(Node root, Node secondLarge) { if(root.right==null) return root.left; Node secondLargest = root; while(secondLargest.right.right==null) secondLargest=secondLargest.right; return secondLargest; } int getmax(node *root) { if(root->right == NULL) { return root->d; } return getmax(root->right); } int secondmax(node *root) { if(root == NULL) { return -1; } if(root->right == NULL && root->left != NULL) { return getmax(root->left); } if(root->right != NULL) { if(root->right->right == NULL && root->right->left == NULL) { return root->d; } } return secondmax(root->right); } In-order traverse the tree. The second last element in the array in the answer. In Python: def find_second_largest_bst_element(root, parent=None): if parent is None: # BST root if root.right is None: # no right subtree if root.left is not None: # if a left subtree exists... return root.left else: # root is the only element of the BST return False else: if root.right is None: # right-most element if root.left is not None: # left subtree exists return root.left else: # leaf return parent else: # check right subtree find_second_largest_bst_element(root.right, root) find_second_largest_bst_element(root) For kth smallest, descend the left subtree first. class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def findKthLargest(root, k): global count if root is None: return findKthLargest(root.right, k) count += 1 if count == k: print root.value return findKthLargest(root.left, k) count = 0 r = Node(10, Node(5, Node(2), Node(7)), Node(30, Node(22), Node(32))) findKthLargest(r, 3) // solution in java // main routine Node findSecondMax(Node root) { if(root == null || (root.left == null && root.right == null) return null; else { Node max = findMax(root); return (max.parent == null) ? findMax(max.left) : max.parent; } } //helper routine, recursive implementation.... can also be done non-recursively Node findMax(Node root) { return (root.right == null) ? root : findMax(root.right); } Show more responses Find the largest number in the binary tree and delete it. And again find the largest number. Short and fast. Reverse in-order traversal of the BST, keeping a count of # of visited nodes. This methods works great to return the kth largest element in a BST. mindpower's solution looks right One or more comments have been removed. |
Given two strings representing integer numbers ("123" , "30") return a string representing the sum of the two numbers ("153") 17 AnswersI don't understand...it's a very stupid question! return Integer.toString(Integer.parseInt("123") + Integer.parseInt("30)); It's not stupid a stupid question. What if the strings have 10000 characters? It's not stupid question, but it's not hard either. I believe the way to do it is to implement the manual addition process by looping through the digits starting from the right to left and adding them one by one. This is an O(N) operation. I'm not sure if there is a better way to do it. Show more responses lol it is a stupid question i agree. All you have to do is parse the strings add em parse em again and return em It is basic but yet not stupid. I assume that the interviewer asked to implement atoi and itoa (in case the interview was in C/C++). The interviewer wanted a loop through the digits starting form right to left, adding them one by one, and keeping track of the carriage. public static String sumStrings(String a, String b){ char[] num1 = a.toCharArray(); char[] num2 = b.toCharArray(); int i = num1.length - 1; int j = num2.length - 1; StringBuilder sumString = new StringBuilder(); int carry = 0; while(i >= 0 || j >= 0){ int d1 = 0; int d2 = 0; if (i >= 0) d1 = num1[i--] - '0'; if (j >= 0) d2 = num2[j--] - '0'; int sum = d1 + d2 + carry; if (sum >= 10){ carry = sum / 10; sum = sum % 10; }else carry = 0; sumString.insert(0, sum); } return sumString.toString(); } public class StringToInt { public int stringToInt(String str) { int tens = 1; int num = 0; for(int i = 0; i < str.length(); ++i) { num += (str.charAt(str.length() - 1 - i) - '0') * tens; tens *= 10; } return num; } public int addStrings(String str1, String str2) { return stringToInt(str1) + stringToInt(str2); } public static void main(String [] args) { StringToInt s = new StringToInt(); System.out.println(s.addStrings("145", "23")); } } @Conner What if the strings are 1000 characters long? does your int tens and int num variables support that? int stringToNumber(char *a){ char *end = a; int it = 1; int acum = 0; while (*end != NULL){ end++; //move pointer to last char of string } while (&end != &a){ acum+=((*end - '0') * it); it *= 10; end--; } return acum; } int sum (char *a, char *b){ return stringToNumber(a) + stringToNumber(b); } import java.util.Arrays; import java.util.Scanner; public class AddNumericStrings { public static void main(String[] args) { final Scanner in = new Scanner(System.in); while (true) { System.out.println("Enter 2 numeric strings : "); String x = in.nextLine(); String y = in.nextLine(); System.out.println(add(x.toCharArray(), y.toCharArray())); } } private static char[] add(char[] big, char[] small) { char[] result = new char[big.length + 1]; Arrays.fill(result, '0'); for (int i = big.length - 1, j = small.length - 1; i >= 0 || j >= 0; i--, j--) { char x = big[i]; char y = '0'; if (j >= 0) { y = small[j]; } int val = x - '0'; val += (y - '0'); result[i+1] += val % 10; if (val > 10) { result[i] += (val/10); } } return result; } } You all know that negative integers exist, right? The question does not specify if the integers are non-negative. One just assume, therefore, that negative integers are possible. It would not be called subtraction. Subtraction does not exist. It would just be addition of the additive inverse. Show more responses Index the tuple to find the 1st & 2nd element. Convert the elements into ints and then convert the answer back to a string. Code: str(int(inp[0]) + int(inp[1])) public static String addTwoStrings(String s1, String s2) { int len1 = s1.length(); int len2 = s2.length(); char[] s1Chars = s1.toCharArray(); char[] s2Chars = s2.toCharArray(); StringBuilder sb = new StringBuilder(); int pointerA = len1 -1; int pointerB = len2 -1; int carry = 0; while (pointerA >= 0 || pointerB >= 0){ int a = pointerA 10) { carry = sumTemp / 10; sumTemp = sumTemp % 10; } else { carry = 0; } sb.insert(0, sumTemp); } if(carry >0) sb.insert(0, carry); return sb.toString(); } One or more comments have been removed. |
To find and return the common node of two linked lists merged into a 'Y' shape. 13 Answershow did the two linked lists make their poses to merge into a 'Y' shape, one's head attached to the waist? please explain more to help understand the question The two linked lists were something like: 1->2->3->4->5 and 3->4->5->6->7->8. For a Y shaped like this: 1 -> 2 -> 3 -> 4 ->7 -> 8 -> 9 5 -> 6 -> 7 -> 8 -> 9 where the trunk portion is of constant length, it is easy. Get the length of the first list. In our case 7. Get the length of the second list: 5. Difference is 2. This has to come from the legs. So, walk the difference in the larger list. Now node1 points to 3. node 2 points to 5. Now, walk through the two lists until the next pointers are the same. Show more responses @kvr what if the lists are 1-2-3-4-7-8-9 and 12-13-14-5-6-8-9 Can this be done using hash tables? Or is there anything more efficient? i think that kvr's answer is the best. @snv if the two lists are linked by the very last two nodes, then you would find out after you are checking the values of the second two last two nodes. you just got unlucky and basically have to check until the very end. so basically, as a diagram with your example, it would look like this 1 -2 -3 -4-7-8-9 x -x -x -x -x-o 12-13-14-5-6-8-9 (sorry about spacing) but because you know the difference in length is 0, you can start comparing the two lists of nodes one by one. from the very beginning. HASH TABLE seems the only efficient wt. 1. add each element's address (of the smallest list)and push it to the hash table. 2. start walking second list. 3. get element compar eits address with hash table if match is found in hash table, return 4. if list is not exhausted, go to step 2. 5. return NULL Hashtable is complete overkill. The point is to realize that the two linked lists have the same tail. That means if you traverse them with the same index but from the right you will eventually find the first similar node. It's almost as easy if the problem said the two linked lists had the same prefix, find the first node on which they split. Here you walk them with the same index from the left. First reverse both list and find point where both gets diverged For Y condition the list could be List 1: 1->2->3->4->5->6 List 2: 7->8->9->4->5->6 So reverse list would be 6->5->4->3->2->1 6->5->4->9->8->7 now compare two list and move forward the position where you find next node of both are different is the point of merging Some of the above will work for doubly linked list. If not, travel node by node simultaneously from each end. When one traversal ends and the postion of cursor at the traversal is the answer kvr's answer is good but I think it could be optimized better by using 2 stacks. Traverse both lists putting each value into 2 separate stacks. Then when both are fully traversed, the head of each stack will match. Pop one off each at a time till they don't match, return the last popped. But I suppose it comes down to where the first match is at. If its the beginning of the list, kvr's answer will be better, if its at the end or bottom half 2 stacks would be better. Let's say L1 is the list starting with the lower number, and L2 is the other Set X = Head of L1 Set Y = Head of L2 While X <= Y Set X = Next(L1) End While If (X==Y) Return X Else While Y<=X Set Y = Next(L2) End While If X==Y Return X End If End If Repeat until you reach the end of either list. |
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. |
Determine if an array from 1..n has a duplicate in constant time and space. 14 AnswersCorrect answer is to place each value in the array in its corresponding index (i.e. if array[x] = 3, put 3 into array[3]). If an index already contains its corresponding value, there's a duplicate. ^^ Sorry, that's linear time *and* at best linear space, you fail. What are the properties of an array that affect time complexity? Usually we're talking about the size of the array, N, such that linear time operations, O(N), are those that perform an operation on each of the elements in the array. However, an important thing to consider is that you can evaluate N (the size of the array) itself in constant time. The only way this can be done in constant time is if the input satisfies the precondition that "1..n" means there are no *missing* values in that range. In other words, such an array from "1..5" must contain at least one instance of the numbers 1, 2, 3, 4, and 5. With that precondition, you know that the length of the array will be 5 if no duplicates and greater than 5 if it does contain duplicates. Show more responses SUM(array) - (N(N+1)/2) = missing number. @Facebook Intern: That wont help .. In case there are 2 duplicates this can be broken. {1, 1, 4, 4} I attach pseudo code here: FindDuplicate(A) i = A.length j = 1 count = 0 while j < i if A[--j] - j == 0 j++ else count++ return count count holds the number of duplicated items This cannot be done in linear time unless the data-structure used to hold the integers has a property that immediately flags duplicates upon insertion. For e.g. like in a Dictionary/HashMap. If an array has elements from 1 to n the size of the array will be n, thus if the size of the array is greater than n, there must exist a duplicate. I think they are just asking to determine if there is any duplicate number ir not. Its not mentioned to find out which number it is. So that we can find out by using sum of n numbers I think they are just asking to determine if there is any duplicate number ir not. Its not mentioned to find out which number it is. So that we can find out by using sum of n numbers They asked for constant time. So checking sum will not work. For zero indexed arrays, Check if arr[len(arr)-1] == len(arr) - 1. Obviously this can't be done with constant time or space. At best you could compute a solution in linear time. memoize/cache it once then you could return the solution in O(1) time for subsequent calls. Show more responses I've seen this question posted several places as "Find if an array has duplicates, in constant O(1) space" but no restriction on time. If the array is not sorted, and there is no restriction on the actual values in each item, then there is no O(1) space and O(1) algo. if you sort the array, then you lose O(1) time and obviously can not detect duplicates even in a sorted array in constant time. If its like most other versions of this question, and its only O(1) space, then you could store the duplicate value in the array itself, overwriting earlier elements that you already scanned. You'd only need an index that points just past the last duplicate value written. But this is not constant time. One or more comments have been removed. |
See Interview Questions for Similar Jobs
- Intern
- Software Engineer
- Software Developer
- Senior Software Engineer
- Software Development Engineer
- Associate Software Engineer
- Software Engineering
- Analyst
- Java Developer
- Consultant
- Engineering
- Business Analyst
- Software Development Engineer I
- Member of Technical Staff
- Test Engineer
- Data Scientist