Software engineer intern Interview Questions
software engineer 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? 59 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. |
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. |
There are 20 floors in a building. If you're on an elevator and you're trying to get to the 20th floor, what is the probability that 4 people ahead of you click the 20th floor before you do? Assuming you click last. 11 Answersassume there is one button for each floor, so 20 buttons. a person can press any 1 button out of the 20, prob is 1/20. Since there are 4 people, so1/16000 These are independent events so the chances of one person before you going to the 20th floor is 1/20. Since this happens 4 times before you the probability is 4*(1/20) or 1/5. The above two are close, but wrong.. There are 20 buttons, thus 20 choices, sure. But you are getting on at one of the floor. No body will press the button for the floor they get on.. Thus, there is really only 19 choices. P = (1/19)^3 (Independent events mean (1/19)(1/19)(1/19)). Show More Responses 1/19 + 1/18 + 1/17 + 1/16 assuming that there were no repeated destinations. based on question: P(all 4 ahead of you want to get off on 20th fl) = (1/19)^4 real life(all 4 want to get off on 20th fl, and one of them is the first person press the button to 20th fl, and that leave all others, including you, stay still): (1/19) * (1/4) about 20% is the right answer. I am surprised with some of the answers, they are all very small possibilities (some less than 1%). I'm quite sure you are all wrong: The real probability is 1 - P(nobody pushes 20) = 1 - (18/19)^3 = 15% If one of the 4 press the button for the 20th floor then the others won't have to do anything. The chances of one of them pressing 20th is: 1/19 + 1/19 + 1/19 + 1/19 = 4/19 The answer is 1-(19/20)^4 One or more comments have been removed. |
Software Engineer Intern at Facebook was asked...
Write a function in language of your choice that takes in two strings, and returns true if they match. Constraints are as follows: String 1, the text to match to, will be alphabets and digits. String 2, the pattern, will be alphabets, digits, '.' and '*'. '.' means either alphabet or digit will be considered as a "match". "*" means the previous character is repeat 0 or more # of times. For example: Text: Facebook Pattern: F.cebo*k returns true 8 AnswersNOTE : I didn't really get the part of : "*" means the previous character is repeat 0 or more # of times. If it can be repeated 0 or more times, that means it's always true... I might have misunderstood this part. This is the code considering '*' and '.' are exactly the same. bool myStringCompare(char* string1, char* string2){ bool match=false; for(int i=0; string1[i] != '\0' && string2[i]!='\0'; i++) { bool condition1 = string1[i]==string2[i]; bool condition2 = (string1[i]=='*' || string1[i]=='.') && (isalpha((int)string2[i]) || isdigit((int)string2[i])); bool condition3 = (string2[i]=='*' || string2[i]=='.') && (isalpha((int)string1[i]) || isdigit((int)string1[i])); if(condition1 || condition2 || condition3) match=true; else{ match=false; break; } } return match; } I have used '#' instead of '*' . this code goes according to the rule that '#' gives 0 or more number of prev character value. #include #include #include bool ifMatch(std::string text, std::string pattern) { int tlen = text.length(); int plen = pattern.length(); std::string output = ""; char prev = '\0'; int k = 0; for(int i=0; i< plen && k < tlen; i++) { char textc = text[k]; char patternc = pattern[i]; if(patternc == '#') { if(prev == '\0') prev = '#'; else if(prev == text[k]) { output = output + prev; k++; } } else if(patternc == '.') { prev = textc; output = output + text[k]; k++; } else if(textc == patternc) { output = output + textc; prev = textc; k++; } else prev = pattern[i]; } std::cout << output << std::endl; if(strcmp(text.c_str(),output.c_str())==0) return true; return false; } int main() { ifMatch("facebook","#m#f.cn#bo#k"); } #include using namespace std; bool regex_match(string s1, string s2); int main() { if(regex_match("facebook", ".*.")) { cout << "Pattern Matched!" << endl; } else { cout << "Pattern Not Matched!" << endl; } return 0; } bool regex_match(string s1, string s2) { char c1, c2; int s2i = 0; for(int i = 0; i < s1.length(); i++) { c1 = s1[i]; c2 = s2[s2i]; if(c2 == '.') { s2i++; continue; } if(c2 == '*') { c2 = s2[s2i - 1]; bool done = true; c1 = s1[i - 1]; for(int j = i; j < s1.length(); j++) { c1 = s1[j]; if(c2 != '.' && c1 != c2) { done = false; i = j - 1; break; } } if(done) { break; } } else if(c1 != c2) { return false; } s2i++; } if(s2i < s2.length()) { for(int j = s2i + 1; j < s2.length(); j++) { if(s2[j] != '*') { return false; } } } else { return true; } return true; } Show More Responses #include #include using namespace std; bool regex_match(string s1, string s2); int main() { string strs[10] = {"facebook", "f.cebo*k", "*", ".*", "facebo.*", "facebo.*k", ".*.", "", " ", ".....o*."}; for(int i = 0; i q; for(int i = 0; i < s1.length(); i++) { q.push(s1[i]); } char last_char; for(int i = 0; i < s2.length(); i++) { if(q.empty()) { return false; } char c1 = q.front(); q.pop(); if(last_char == '\0') { last_char = c1; } if(c1 == '.') { last_char = c1; continue; } if(c1 == '*') { if(last_char == '.' || last_char == '*') { last_char = c1; break; } bool done = true; for(int j = i; j < s2.length(); j++) { if(s2[j] != last_char) { done = false; i = j - 1; break; } } if(done) { last_char = c1; break; } } else if(c1 != s2[i]) { return false; } last_char = c1; } if(!q.empty()) { while(!q.empty()) { if(q.front() != '*') { return false; } q.pop(); } } return true; } boolean accepts(char* pattern, char* s) { if (!pattern || !s) return 0; if (0 == *pattern) return (0 == *s); if ((strlen(pattern) > 1) && (pattern[1] == '*')) { return (match(pattern, s) && accepts(pattern, s+1)) || accepts(pattern+2,s); } else { return (match(pattern, s) && accepts(pattern+1, s+1)); } } boolean match(char* pattern, char* s) { return ((*pattern == '*') || (*pattern == *s)); } @Rahul: a small bug there (matching the '*' rather than the '.'): boolean match(char* pattern, char* s) { return ((*pattern == '*') || (*pattern == *s)); } should be: boolean match(char* pattern, char* s) { return ((*pattern == '.') || (*pattern == *s)); } Other thoughts: -- "if ((strlen(pattern) > 1)" is redundant since "if (!pattern[1] =='*')" takes care of it. (and I'd generally avoid a strlen in either a loop or recursive call) -- This solution ends up with a stack depth that is equal to the length of the target string -- far from ideal. #include using namespace std; bool match(string s1, string s2) { bool matching = true; char c1 = s1.at(0), c2 = s2.at(0); unsigned int i = 0, j = 0; while(matching && (i 0 && c1 == s1.at(i - 1)) { i++; } else if(c2 != c1) { matching = false; } i++; j++; } return matching; } int main() { bool m = match("faceboooooook", "f.cebo*.k"); if(m) { cout<<"matching"< public class MatchTwoStrings { public static void main(String[] args) { String s = "F9ceboooooook"; String t = "F.cebo*k"; String td = ""; for(int i=0; i |
Software Engineer Intern at PayPal was asked...
n= 20 for (i=0;i<n; i--) print i the question was to change or replace a only one character in for loop to print 20 times. 9 Answersit has to do with decrement or condition clause in for loop n= 20 for (i=0;-i n= 20 for (i=0;i Show More Responses add 4 in front of the 0 (in i=0); so it becomes i=40; i < n (which is 20); i-- changing i-- to n-- is a correct answer. adding 4 in front of i=0 would work, but does not satisfy the condition "change or replace a character" as it adds a character instead. < stands for '<' and replace '-' with '+' for i in the increment part of for loop. Swap i— with n— One or more comments have been removed. |
What is the angle between the two arms of the clock at 2:40? 8 Answersint time(int h, int m) { angleH = (h*360)/12; angleM = (m*360)/60; return Math.abs(angleH - angleM); } 160 degrees if a circle is bisected, the degree would be 180, as a circle is 360 degrees. How do you come up with 160? Show More Responses 160 of course http://en.wikipedia.org/wiki/Clock_angle_problem#Equation_for_the_angle_between_the_hands This should help http://www.mathcelebrity.com/clockangle.php?num=2%3A40&pl=Calculate Hours needle move with mins needles. Think about in one hour the hr needle move 30 degree. And 40 mins the hr needle move 20 degree. At time of 2:40, hr needle move 80 degree, mins move 240 degree. The angle between two needles will be 240-80=160. One or more comments have been removed. |
Software Engineer Intern at eBay was asked...
Questions related to data structures like "What data structure would you use for a browser's BACK & FORWARD ability" 7 AnswersMay be Stack , any one please correct me if I am wrong. This can be implemented by using two different stacks, one for back and one for forward. Command Pattern Show More Responses I would use doubly link list Doubly linkedList Use two stacks. Every time you visit a site, push its address in stack1. When you press back, pop from stack1 and also push in stack2. When user presses forward, pop from stack2 and also push in stack1. two stacks. When you visit a site, push its address into stack1 and clear stack2; When you press back, pop the address from stack1 and push the same address into stack2; When you press forward, pop the address from stack2 and push the same address into stack1. |
Software Engineer Intern at Hulu was asked...
Write a power function power(a , b) returns a^b 8 Answersint power (double a, int b) { for (int i = 1, i <= b, i++) { a *= a; } return a; } There are some conditions you are missing. What if b is <=0 ? The conditions made by the Hulu rep was to assume b > 0. However there is a better way to do this problem. Show More Responses long power(int a, int n) { if(n%2==0) return power(a,n/2)*power(a,n/2); else if (n%2==1&&n!=1) return power(a,n-1)*a; else //n==1 return a; } def power(a,b): if b is 1: return a return a * (power(a, b--)) double pow(int a,int b) { if(b0) { if(b%2==1) res*=a; a*=a; b>>1; } return res } def power(a, b): return a**b One or more comments have been removed. |
Software Engineer Intern at Facebook was asked...
Generate a new array from an array of numbers. Start from the beginning. Put the number of some number first, and then that number. For example, from array 1, 1, 2, 3, 3, 1 You should get 2, 1, 1, 2, 2, 3, 1, 1 Write a program to solve this problem. 7 Answersint[] Reformat(int[] original, int length) { LinkedList list = new LinkedList(); int currentCount; for(int i=0;i function numberArray( $arr ){ $a = array(); $number = null; $c = -1; foreach( $arr as $v ){ if( $v != $number ){ if( $number ){ $a[] = $c; $a[] = $number; } $number = $v; $c = 1; } else { ++$c; } } if( $c > 0 ){ $a[] = $c; $a[] = $number; } return $a; } var_export( numberArray( array( 1,1,2,3,3,1 ) ) ); $val) { echo $val . "\t"; } echo " \n"; } ?> Show More Responses working in php: sizeof($list)-2) || ($list[$i]!=$list[$i+1])){ $result[]=$count; for($j=0;$j vector reformat(int arr[], int size) { vector res; int j, count = 0; for(int i = 0; i < size; ) { cout << i << endl; count = 0; for(j = i; j < size; j++) { if(arr[j] != arr[i]) break; count++; } res.push_back(count); res.push_back(arr[i]); i = j; } return res; } int i=0; int j=1; ArrayList array=new ArrayList(); while(i @Anonymous: Your inner while loop will cause an out-of-bounds exception to be thrown when your scanning hits the end of the array. Your while loop will try to access givenArr[i+j] even when j increments to the point that surpasses the length of the array. You need while((i+j) != givenArr.length ... ) |
Write a function that finds the minimum and maximum values within an unsorted array using divide-and-conquer. 6 AnswersThe best I can do in Java: int findMinimum(int[] a, int start, int end){ if (end-start == 0){ return a[end]; } if (end-start == 1){ if (a[end] = 2){ int split = (start+end)/2; int leftLeast = findMinimum(a, start, split); int rightLeast = findMinimum(a, split+1, end); if (leftLeast void GetMinMax(int[] array, out int minValue, out int maxValue) { if (array == null || array.Length == 0) throw new ArgumentException("array null or empty."); MinMax minmax = GetMinMax(array, 0, array.Length - 1); minValue = minmax.Min; maxValue = minmax.Max; } MinMax GetMinMax(int[] array, int begin, int end) { if (begin == end) return new MinMax { Min = array[begin], Max = array[begin] }; else if (begin + 1 == end) return new MinMax { Min = Math.Min(array[begin], array[end]), Max = Math.Max(array[begin], array[end]) }; else { int mid = begin + (end - begin) / 2; MinMax left = GetMinMax(array, begin, mid); MinMax right = GetMinMax(array, mid + 1, end); return new MinMax { Min = Math.Min(left.Min, right.Min), Max = Math.Max(left.Max, right.Max) }; } } struct MinMax { public int Min; public int Max; } #include #include void devide_conque(int*, int, int, int*, int*); int main(int argc, char** argv) { int min, max; int i = 0, array_size = (argc - 1); int* array = (int*) malloc(sizeof(int) * (argc - 1)); for (; i rmax ? lmax : rmax; } } Show More Responses public static int[] minMax(int[] a) { int[] mm = new int[2]; if (a.length > 0) { mm[0] = a[0]; mm[1] = a[1]; } mm = minMax(a,0,a.length-1); return mm; } public static int[] minMax(int[] a, int low, int high) { int[] temp = new int[2]; if (low+1 < high) { int mid = (low+high)/2; int[] temp1 = minMax(a,low,mid); int[] temp2 = minMax(a,mid+1,high); temp[0] = Math.min(temp1[0],temp2[0]); temp[1] = Math.max(temp1[1],temp2[1]); return temp; } else if (low <= high) { if (a[low] < a[high]) { temp[0] = a[low]; temp[1] = a[high]; } else { temp[0] = a[high]; temp[1] = a[low]; } } return temp; } def find_min_max(arr): return min_max(arr, 0, len(arr)-1, 1e308,-1e308) def min_max(arr, i, j, mn, mx): if not arr or i > j: return mn, mx elif i == j: return min(mn, arr[i]), max(mx,arr[i]) else: mid = ( i + j) / 2 left = min_max(arr, i, mid-1, min(mn, arr[mid]), min(mn, arr[mid])) right = min_max(arr, mid+1, j, min(mn, arr[mid]), max(mx,arr[mid])) return min(left[0], right[0]), max(left[1], right[1]) first divide list in two, compare number from each list so we got 1list where the minimum is and second list where maximun is. Search for the min in the first list and the max in the second list. $list[$n-1-$i]){ $temp = $list[$i]; $list[$i] = $list[$n-1-$i]; $list[$n-1-$i] = $temp; } } $min = $list[0]; for($i=1;$i$max) $max=$list[$i]; } $result = array('min'=>$min, 'max'=>$max); return $result; } ?> |
See Interview Questions for Similar Jobs
- Software Engineer
- Intern
- Software Engineering Intern
- Software Developer
- Senior Software Engineer
- Software Development Engineer
- Software Engineering
- Data Scientist
- Technology Analyst
- Product Manager
- Engineering
- Analyst