A list of amazon questions and answers from glassdoor.
A list of amazon questions and answers from glassdoor.
Questions |
---|
question :
Before this review ends, I’d like to offer some suggestions. 1) Don’t think about the money. If you go into the field of engineering, you’re going to make a lot of money either way. If you want this job, make sure its because you love doing what the job description says. Make sure you love the company, and the people. Otherwise, no matter how much money it may be, you will hate it, and yourself for wasting your time on something that wasn’t important to you. Loyalty is important, but remember to stay loyal to yourself first. Interviews can read you and see if you’re the type that is in it for the $$$ and will skip town after getting the bonus at year’s end, or if you’ll be the one they can rely on. 2) Although the interview does not require you to be in a certain attire, use your best judgment. Eitherway, please look at weather.com and don’t be arrogant and think you can handle the cold. IT"S COLD! Buy a thick coat, bring an umbrella, and dress warm. Don’t get sick. And GET PLENTY of SLEEP!!! Seriously… 3) They do reimburse you for expenses, to a certain extent, don’t go overboard… And they do NOT reimburse for alcohol, so don’t even think about trying to ask. On the first night, I ate a basic meal of subway and thai. The law of interviews, as passed down in my family, suggests one rule: NEVER PUT SOMETHING IN YOUR BODY THAT YOURE NOT USED TO BEFORE AN INTERVIEW. If you’re not used to seafood, don’t eat it the night before, you may get sick. Eat it after. And DON’T DRINK at least two days before an interview. After the interview is over, go out on the town, check out Pike Market, and try some cool foods. 4) Be yourself. Try not to be nervous, they were once in your seat too. 5) Don’t bluff anyone. Don’t try to impress them with something if you don’t know it. Be honest. In the end, it’ll help you. 6) They say check in at least 15 minutes early. I say, GET THERE 30 to 45 minutes early because there will be traffic, and taxi’s aren’t easy to get a hold of from your hotel. Sit in the lobby with other people and TALK TO THEM, relax, laugh, and enjoy it. 7) GET TO THE CHOOPPPA early. Seriously, don’t be late for your flights in or out of SEATAC. If you’re not used to SEATAC, There is a train inside the airport that will take you to your gate. TSA takes about 20 minutes to get through. Always come early. 8) Taxi’s and food are expensive, and although they do take plastic. Use cash. You don’t want to deal with a stolen credit card on trips during an interview. You don’t need the stress. If you are there for approximately 2 nights and 3 days, or even 1 night and 2 days, take approximately $300in cash. Transportation to and from the airport will be about $100 total. Food for the trip will be about $50 a day. And chances are, you’ll want to use the remaining $50 to buy gifts or souvenirs (Obviously Not reimbursed). 9) I highly recommend WALKING and NOT GETTING A CAR. Parking is very expensive and near impossible. Think about the show FRIENDS or HIMYM when thinking of getting a car, they take tax or walk… You’ll do the same. Walking anywhere in town is easy and the preferred choice. Do it. Just wear a coat. 10) Watch Lion King 1, Mulan 1, and Back To The Future 3 at somepoint before you interview. Those movies have certain characteristics that will encourage you, make you happier, and make you feel confident in yourself. You don’t need alcohol for that. Maybe some Phad Thai. And either way, enjoy it. |
answer: Great writeup, very helpful! |
answer: Good read and insightful. Not to sound too prying how can one apply for such positions do we need to have contacts or is it fair process. |
question :
Write OOP system to parse different type of error formats. |
answer: What is the answer of this question? |
answer: Here is what I would answer. I think what they are looking for here is a description of the strategy pattern. But as always I would start out asking questions (like the requirements definition phase).What is the bigger picture of this component? What sort of system does it live in? Are there specific time or program size constraints? Who are the end users? Who are the clients? How are errors to be parsed delivered?Without many details, the most flexible implementation of the error parse would be a Strategy which would dynamically allow different parsing algorithms.I’ll define an abstract base class (ErrorParse) with 1…n subclasses (UserErrorParse, SystemErrorParse, FastErrorParse, ScoobyDooErrorParse, …NErrorParse).The base class defines the interface for parse which the subclasses will use. Each subclass will implement the "parse" method as it pertains to it. This has a few benefits:This allows the elimination of a large set of conditionals that would choose which parsing algorithm to use, which would result in better maintainable code.the derived classes could share common methods.This would allow a client the ease of altering the parse algorithm at run time to adjust for time or data constraints or perhaps depending on the level of detail a particular client would want. You could even use abstract factory here to define a strategy that matches a suite of other classes that would be specific to a family of clients in the case where you don’t want a client deciding which parse implementation it gets to use. Or the client could have some flexibility and specify it wants the error parsed urgently, or with a lot of detail. Using strategy easily accommodates all of that. |
question :
Implement a data structure like a stack but with a way to find a max at O(1) time. |
answer: Later found out this was in Cracking the Coding Interviews. |
answer: There are several ways to do this. You push two numbers onto the stack whenever you add, first pushing the new number and then the max of the new number and whatever was below it. If you are allowed to store the max value in a field in the stack implementation you can write a normal stack implementation, except when a new value is equal to or greater than the old max, first push the old max onto the stack. then when you call get max you get pop until the value = the max you stored, and the next value you pop is the new maximum. |
question :
How will you find the middle node in a linked list |
answer: Slow pointer, fast pointer. Slow at the pace of one node and fast at the pace of two nodes. By the time fast pointer reaches end of list, slow pointer is at the middle position. |
answer: #include<iostream>using namespace std;struct Node{ Node *next; int data;};Node* findMidofLinkedList(Node* head){ Node *fast = head; Node *slow = head; while (fast->next != NULL && fast->next->next != NULL) { fast = fast->next->next; slow = slow->next; } return slow;} |
question :
How will find if an integer is power of 2. |
answer: public static boolean isPowerOf(int number, int base){ while(true){ if(number==1) return true; if(number%base != 0) return false; number = number/base; } } |
answer: /* from Cracking the coding interviews" book */public boolean isPowerOfTwo(int n){return (n & n – 1) == 0} |
question :
2nd largest number in an array |
answer: (1) nlogn. sorting.Or.If numbers have small range, use a each number’s value as a index. Create a table, each number goes into the corresbonding index. when done, iterate backwards. Should give you O(n) time.(2) bit counter, right shift, &1. gives you number of ones.(3) two pointer, one goes one step at a time, another one goes two steps at a time. If they meet, then there is a loop. Further question: how can you find the start of the loop?..ask me if anyone needs details. |
answer: Order statistics. in O(n) time. Kth largest element. if there are n element then we can find (n-1)th element in O(n) time |
answer:
This post has been removed. Please see our |
question :
Implement a program to find whether a number is even or odd without using arithemetic operator |
answer:
This post has been removed. Please see our |
answer: This can be solved by checking the last bit of the number. if it is 0 then even else odd.So, if number is n. You can do n&1 and then check whether this number is 0 or not. |
question :
3) Given a N*N array where N is even such as 4, 8 and so on . Print the array from the center. a= [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] the output should be [6 10 12 7 3 2 1 5 9 13 14 15 16 12 8 4 ] . |
answer: There is a certain pattern in the printing, and there s a fixed amount of jump in each iteration.We move down , left up and right in that order and after one round we increase the jump value by 2 after every round . |
answer:
This post has been removed. Please see our |
answer: i guess this is spiral order traversal but the traversal is starting from mid |
question :
Explain to a high school student with limited computer knowledge how a CPU is capable of running two programs simultaneously. |
answer: Context switching, and interrupts. The computer switches between the two programs so quickly and constantly that it seems as though both programs are running at the same time, when in reality they aren’t. |
answer:
This post has been removed. Please see our |
question :
Write a function to merge two sorted linked lists. If you were to incorporate this functionality into the standard library, how would you implement it so as to "benefit from the OOP goodness" |
answer: Node MergeLists(Node list1, Node list2) { if (list1 == null) { return list2; } if (list2 == null) { return list1; } if (list1.data < list2.data) { list1.next = MergeLists(list1.next, list2); return list1; } else { list2.next = MergeLists(list2.next, list1); return list2; }} |
answer:
This post has been removed. Please see our |
question :
I was asked two questions. Q 1. You are given two version numbers of a software, like Version 10.3.4 and Version 10.3.41. Write a program to find out which of the version numbers are the latest. If version 1 is latest output -1, if version number 2 is latest output +1 else output 0 if same version. Both the version numbers are taken as string. He also asks to make the program of minimum time complexity as we can. At the end he also asked the difference between an iterative program and one with recurrence and their advantages and disadvantages. Q 2. Given two files with a list of application IDs (or some kind of data) stored in them , write a program to compare the data in the two files and output all the common data found in each. What data structure would you use and why ? Give a minimum time and space complexity algorithm. Why did you choose the particular data Structure or algorithm ? |
answer: 1. This was a little tricky. You have to check for the decimal place in both the versions and then Store that part of the string till the decimal place in a temporary variable and then convert them to integer and check which one is greater. You have to keep on doing that till you reach the end of the version numbers or till when you find the answer2. In the second question you can use Linked lists and then Binary Search Algorithm. The interviewer will ask you the reason for this. |
answer: Why not just delimit the string with "."Then you’ll have an array of string numbers.Then loop with the array from 0 -> n (depending on how many decimals there was)and compare. Return when one is greater than the other.You will have to check if you get a index out of bounds if one has more decimals than the other.Over all, that should be in n time. |
answer: As for #2. HashTable it. Also n time. |
answer: If you are using c++, can’t you just use the "compare" method that is built into the string class? |
question :
How would you implement Amazon’s "users who bought this item also bought …" feature? |
answer: I think we can implement it by adding some tags to all the product and then rank it. suppose someone bought a camera, so we will search for the products which are having same tags but lower order, like a tripod is having the lower order than a camera. because a person will only think about the tripod after having a camera. again, we can show the feature of you might be interested in this by adding the higher ranked tags, like some other camera. |
answer: Apriori Algorithm in the transactions and items dataset would give the results, Market Basket/Affinity Analysis would be the term to search for. |
answer: http://nikhilvithlani.blogspot.com/2012/03/apriori-algorithm-for-data-mining-made.htmlu can chk the apriori algo over here |
question :
None….all questions generally behavioral. |
answer: What was a difficult situation where you have to convince someone to follow your leadership and how did you convince them? |
answer: How many rounds did you have, even the final call & on-site were behavioural? |
question :
To copy a linked list. Every node’s prev points to the previous node, but the next points an arbitrary node. |
answer: Since the nodes have both "next" and "prev" pointers, this sounds like a doubly-linked list. Ask if that is the case and whether the list’s "tail" pointer points to the correct node, then just use the tail and prev pointers to iterate through the list backwards, prepending each element to your new list.If the original list doesn’t have a tail pointer, or if it doesn’t point to the correct node, then it *may* not be possible. To be possible, you must know the length of the list. If you DO know the length of the list, you can try iterating through the "next" pointers until you find a node with a "prev" trail the same length as the list. If you find one, it’ll be the tail node and you can do as above.Note, however, that the sequence of "next" pointers may form a cycle without ever pointing to the true tail. You can ask if this is a possibility — if so, you’d need to check for cycles as you iterate through the "next" pointers (you can use the tortoise-and-the-hare algorithm within the same while loop). |
answer: Insert a copy of each node after the node it’s copying, so the list looks like this:Node1.next -> Node1cpy.next -> Node2.next->Node2cpy.next,Then basically you make two more passes, one two nodes at a time looking like this:Node1.next->arbitrary = Node1.arbitrary->next;Then split the lists:Node1.next = Node1.next->next;Node1Cpy.next = Node1Cpy.next->next; |
question :
get the second most highest integer from an array |
answer: 1. sort array2. take second last number |
answer: wrong, you can do it o(N), sort takes nlong, you can simply have two max1, and max2, keeping in mind which one is the biggest, and then as you go through the array swap or replace them:assume max2 > max1 to start with : max1 = a[0] < [a1]:a[0] ? a[1]max2 = a[0] > [a1]:a[1] ? a[0]if (a[i] > max2 ){max1 = max2;max2 = a[i];}else if(a[i]> max1){max1 = a[i]} |
answer: O(N) is less efficient than O(N log N) |
answer: O(N log N) is NOT more efficient than O(N)… |
answer: In what universe is O(N) is less efficient than O(NlogN) ? |
answer: you can build_max_heap in O(n) …..2nd largest will be greater child of root. |
answer: Here is my answer. I try to be as verbose as possible with all my assumptions because I hear the interviewers want to hear the way you think.There are just a handful of comparisons that need to take place for each element so it it would be O(n) linear time in execution.I did use 2 integer variables to store the highest and second highest. Since no magic value was defined for an integer that could never appear in the list, I also needed 2 flags to tell me if each storage integer had been pulled out of the list or was still the initial value.If I needed the nth highest, I would need to come up with another solution. I would probably opt to sort the array unless n was very small relative to the list size.My code will handle the case where there are duplicate integers. I also assumed you could have negative integers in the array. It also has some error handling built in and handles the error with a printf.I chose C++ because I’m most comfortable with it and the ability to declare variables whenever you want. I could have easily made this a standard C program.#include "stdlib.h"#include "stdio.h"#include <iostream>#define SIZE_OF_ARRAY 11int array[SIZE_OF_ARRAY] = {-1, 0, 200003, 9, 2, 3, 4, 5, 6, 7, 8};int main(){ int highest = 0; int _2nd = 0; bool highest_set= false; bool _2nd_set= false; for(int i = 0; i < SIZE_OF_ARRAY; i++) { if(highest_set == false) { highest = array[i]; highest_set = true; } else { if(array[i] > highest) { //we have a new highest! //if 2nd highest hasn’t been set yet, put highest there if(_2nd_set == false) { _2nd_set = true; _2nd = highest; } //or if 2nd highest has been set, compare it to see if it //highest is greater or equal. set it if it is. else if(highest >= _2nd) { _2nd = highest; } else { printf("Error: somehow highest got to be greater than 2nd highest\n"); } //set highest to the array value. highest = array[i]; } else if (_2nd_set == false) { //2nd hasn’t been set yet so set it. _2nd = array[i]; _2nd_set = true; } else if(array[i] > _2nd) { //a higher 2nd. _2nd = array[i]; } else { //nothing to do array[i] is less than both highest and 2nd and //both have been set already. } } } printf("The 2nd Highest is %d\n", _2nd); //cout << "then" << endl; return 0;} |
question :
There was no unexpected or difficult Question. 1. Find the first non repetitive character in a character stream. 2. Check for prime number and Elevator system design. 3. Agent bidding system design 4. Find for subtree within a larger tree. |
answer: 1.Character prev = null;Character current = null;while(null != (current = getNextChar(stream))){ if(prev = null){ prev = current; } if(prev != current){ break; }}//current contains first non repetitive char |
answer: the stream has assorted characters.. the above solution does not work. |
answer: use a hash table and index |
question :
make a function that counts the number of nodes in a tree |
answer: use a queue |
answer: Use recursion, it’s the best at problems like this! Think of the problem in these terms:1.) An empty tree has 0 nodes2.) Any other tree has one root node, plus however many nodes are in the left and right sub-trees.Now think of how to put that into code. |
answer: A non-recursive approach is to perform a breadth-first traversal and and count the nodes as you visit them.Specifically, suppose we have a class of type Node that contains two fields, called left and right, both of type Node. Let root (of type Node) be the root of the tree. Here’s the code, which you would invoke with the call: nNodes = countNodes( root );public int countNodes( Node node ) { int count = 0; Queue<Node> q = new LinkedList<Node>(); if ( node != null ) { q.add( node ); } while ( !q.isEmpty() ) { count += 1; Node traveler = q.remove(); if ( traveler.left != null ) { q.add( traveler.left ); } if ( traveler.right != null ) { q.add( traveler.right ); } } return count;}Hope this is useful! |
question :
Most of them were expected. Almost all are problem solving questions. 1. Given a BST with following property find the LCA of two given nodes. Property : All children has information about their parents but the parents do not have information about their children nodes. Constraint – no additional space can be used |
answer: Hint – detect the level at which the given nodes are present. Then travel upwards from that position. |
answer: How about traversing from one node to root, adding each node to hashset, Then try do the same with second one, on collision return node. |
answer: No, you cannot do that since you need extra space for hashset which is not allowed, I am going to post my solution in a min |
answer: function findLCA(Node node1, Node node2){ int counter1 = 0; int counter2 = 0; Node temp; //Find the level for each node, use a temp node to //traverse so that we don’t lose the info for node 1 and node 2 temp = node1; while( temp.parent ! = null) { temp = temp.parent; counter1++; } temp = node2; while( node2.parent ! = null) { node2 = node2.parent; counter2++; } /* * We wanna make them at the same level first */ if(counter1 > counter2) { while(counter1 != counter2) { node1 = node1.parent; counter1–; } } else { while(counter2 != counter1) { node2 = node2.parent; counter2–; } } while (node1.parent != node2.parent) { node1 = node1.parent; node2 = node2.parent; } System.out.println("Found the LCA: " + node1.parent.info);} |
answer: //correctiontemp = node2;while( temp.parent ! = null){ temp = temp.parent; counter2++;} |
answer: @chmielsen : your solution would work… but as said by Hamid, due to the constraint of space, you have to consider some other technique. |
answer: I seems really like the question of finding intersection of two linked lists |
answer: 1)consider node1 as p1. see if p1=p2 , p1->parent=p2, p2->parent=p12)now for a value p1 try to see recursively if p2->parent ever becomes equal to p1 or p2=root3)set p1=p1->parent and continue till p1=p2 or p1= root |
answer: temp1 = node1;temp2 = node2;while( temp1.parent != null && temp2.parent != null){ if(temp1.value == temp2.value){ return temp1; // temp1 and temp2 point to same node so pick one } temp1 = temp1.parent; temp2 = temp2.parent;}System.out.println("no such ancestor"); |
answer: Consider this is a BST, where max node is always on the right of min node, we can traverse max upward one node at a time while comparing min nodes as it traverse upward toward root.BinaryNode findBSTLCA( BinaryNode min, BinaryNode max ) { BinaryNode tempMax = max; BinaryNode tempMin = min; while( tempMax != null ) { while( tempMin != null ) { if( tempMin.element == tempMax.element ) return tempMin; tempMin = tempMin.parent; } tempMin = min; // reset tempMin tempMax = tempMax.parent; // traverse tempMax upward 1 node } return null; // no LCA found} |
question :
2. Find top 100 maximum number from a continuous input stream. |
answer: Use a min heap to store the top 100 maximum numbers. If the incoming number is greater than the top element replace it and sort the heap. |
answer: Use a sorted generic list.If the number of elements is < 100 Add the incoming number to the list.else if the incoming number is greater than the zero element of the list Add the incoming number to the list remove the zero element from the list to keep the number of elements at 100. |
answer: The interview candidates solutions is the best, n insertion * log n for each heap insert – > nlognDeveloper: n * n = n^2 |
answer: I think the key of the question would be 100, a fixed number.The sorting time of 100 numbers would always be O(1). |
answer: There is a blog discussing a similar coding interview question at http://codercareer.blogspot.com/2011/09/no-05-least-k-numbers.html.The first solution is suitable for this problem. |
question :
A vaguest ion that was asked in a very general way, but which the interviewer clearly had specific answers he was looking for: "what are four components that are included in every specification doc". That sounded a lot like a thing you would find at Microsoft and similar large companies where process is more strictly defined. I answered poorly, I think, perhaps because I haven’t worked with that kind of spec in a very long time, and not on any projects that worked out well. Smaller orgs/programs/projects (startups and incubators, for example, where the outcome is always in flux, as I am accustomed to working with) can have poor specs, specs that are centered on marketing, planning documents that are made up of wireframes and time-based stage gates. In any case, I choked a bit, and the interview kind of skated around and became more specific as we went along. I don’t think that is inappropriate, though, because Amazon does value and expect the ability to deal with ambiguity. |
answer: Description of the current state, problems in the current state, Description of proposed state, advantages of proposed state. |
answer: "what are four components that are included in every specification doc"This question is insane, and I would hate getting an interviewer that asks such a question. Correct answer can be: "1. Title, 2. Author, 3. Requirements, 4. Version". If the title "requirements doc" is not there, maybe it is not a requirement doc.Specific sections are: http://en.wikipedia.org/wiki/Product_requirements_document |
answer: The toughest interviewer with the "4 components" question was a dev, in fact. The TPM screen was not so academic, more about challenges and solutions, philosophy, team fit, familiarity with the specific technology and business. That was definitely the screen that didn’t go well, although he was wicked smart and wasn’t just trying to mess with the candidate or anything. |
question :
How would you code up a custom rectangle detector? |
answer: can you elaborate the question. |
answer: As the interview was for a software engineer position, the likely problem could be "given the four coordinates, find out if they make a rectangle".I would probe if there any constraints first. If the sides of the rectangle can only be parallel to the axis, then the problem is simple (just test whether Xs, and Ys are the same).It is important to understand whether the coordinates can be given out of order, or, follow a specific pattern (clockwise, top left first, etc.). Knowing that, can also simplify the calculations. Also, depending on the requirements, the same set of coordinates can be considered valid or not valid rectangle.If the rectangle can be tilted on a plane, you need to use some geometry. I wouldn’t expect a software engineer to remember the details from the basic geometry, but calculating the length of the segments and/or the angle between them will get you the answer.Ask for special cases, as, can a zero width rectangle be considered a rectangle? Can coordinates be negative, what happens with overflow for signed values, etc. |
question :
How would you code up a custom rectangle detector? |
answer: I suggested something about matching intersecting hough lines. |
answer: Hi… Could you plz explain what is a custom rectangle detector…I hav my interview with Amazon on monday … plz help |
answer: By a custom rectangle detector I mean how would you write your own function to detect rectangles. Your input would be the pixel data and your outputs would be something like the x,y locations of the rectangles. |
question :
What is the range of numbers that can be stored using a single byte? |
answer: Signed: From ?128 to 127. Unsigned: From 0 to 255. |
answer: I think the range can be anything you want it to be, just have to agree on the storage format. Imagine a situation where you have to store only the even positive numbers, that means the range can be 0..512. If you know that the lowest number can be 100, then the range can be 100..612. Using more elaborate formats you can encode any range in a byte (with low precision, possibly). |
question :
Given two lists containing any kind of objects, build a function that takes them as input and outputs a list of common/different elements. |
answer: For x in l1 For y in l2 If(x == y): print x |
answer: I don’t think your solution will work..If it is Java, maybe you can get away with x.equals(y)..the code above will most likely throw some form of exception or give you incorrect results |
answer: Assuming your object can be compared somehow, you can put the smaller list into a "common" hash with (Object, 0) and then loop through the second list, incrementing the value to 1 for all existing Objects in the hash. For objects not in the hash, put them into a "different" hash. Then you can loop through the "common" hash to find all the values of 1, and return those as a list of common elements. Same with the "different" hash |
question :
Calculate the square root of a number. |
answer: public double squareRoot(double x) { double epsilon = 0.000001; double base = 0; double increment = 1; while (increment > epsilon) { double diff = base*base – x; if (diff < 0) { base += increment; } else if (diff > 0) { base -= increment; increment /= 10; } else { break; } } return base; } |
answer: private static double sqrt(double n) { double lower = 0; double upper = n; for (int i = 0; i < 1000; i++) { double mid = (lower + upper) / 2; if (mid * mid < n) lower = mid; else upper = mid; } return (lower + upper) / 2; } |
answer: #include<iostream>#include<math.h>using namespace std;#include <stdlib.h> int main(){float n;cout<<"Enter No:";cin>>n;if(n<0) { cout<<("negative don’t have square roots"); exit(0); }float y=sqrt(n);cout<<"sqrt is "<<y;return(0);}float sqrt(float n){float low=0,high=n;float mid=(low+high)/2;while(fabs(mid*mid-n)>0.00001){if(mid*mid<n)low=mid;else if(mid*mid>n)high=mid;mid=(low+high)/2;}return mid;} |
question :
1) A puzzle to find 3 numbers in an array which summed to 0. |
answer: Sort the array (N Log N). Then, for each i, keep two pointers j at the beginning and k at the end of the subarray{i -> N]. If subarray[j] + subarray[k] + subarray[i] = 0, you’re done. If the sum is positive, then move k back. If the sum is too small, then move j forward. Try this until j > k, at which point, increment i, and do this again with j = i and k = N initially. You’ll have O(n^2). |
answer: Classical Computer Science problem… http://en.wikipedia.org/wiki/3SUM |
answer: Classical Computer Science problem… http://en.wikipedia.org/wiki/3SUM |
answer: def sumOfThree(inputList): A = sorted(inputList) for i in range(len(A)): j = i k = len(A) – 1 # -1 is to account for python’s zero-based index while (k >= j): sumOfThree = A[i] + A[j] + A[k] if (sumOfThree == 0): print A[i], A[j], A[k] # return (A[i], A[j], A[k]) # We didn’t match. Let’s try to get a little closer: # If the sum was too big, decrease k. # If the sum was too small, increase j. if sumOfThree > 0: k -= 1 else: j += 1sumOfThree([-1,-2,-3,-4,1,2,3]) |
question :
Given any string, find the index of the start of the first duplicated 3-letter subsequence. For example, in abcabcdef, it would be 0, and abcdefdef would be 3, and then abcdefkajdkffatabcdef would be 0, and abcdefkajdkffatdef would be 3. |
answer: Tried brute forcing it, O(n^2) too bad. Did it using HashTables. |
answer: Here is an O(N) solution with HashMap.By the way, I think the fail case should be -1 instead of zero since zero is a valid possibility. public static int findDuplicate3Chars(String s) { HashMap<String, Integer> map = new HashMap<String, Integer>(); StringBuilder b = new StringBuilder(); int inputLength = s.length() – 3; for (int i = 0; i < inputLength; i++) { for (int j = 0; j < 3; j++) { b.append(s.charAt(i + j)); } String key = b.toString(); if (map.containsKey(key)) { return map.get(key); } map.put(key, i); b.setLength(0); } return -1; } |
question :
print all permutations of a string |
answer: Here is the answer for integers. Strings would have an identical algorithm. public ArrayList<ArrayList<Integer>> findPermutations(ArrayList<Integer> integers) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (integers == null || integers.size() == 0) { return result; } for (int i = 0; i < integers.size(); i++) { ArrayList<Integer> subArray = new ArrayList<Integer>(); for (int j = 0; j < integers.size(); j++) { if (!integers.get(j).equals(integers.get(i))) { subArray.add(integers.get(j)); } } ArrayList<ArrayList<Integer>> subResult = this.findPermutations(subArray); for (ArrayList<Integer> subPerm : subResult) { subPerm.add(integers.get(i)); result.add(subPerm); } ArrayList<Integer> selfResult = new ArrayList<Integer>(); selfResult.add(integers.get(i)); result.add(selfResult); } return result; } |
answer: For question like this, the best way to do is recursive not iterative |
answer: Vector<String> & Find_Substring_Permutation(String & s, int n) { Vector<String>::iterator g; Vector <String> a,b; // base case if (n==s.length()) return; for(int i=0;i<s.length()-n;i++) { b = Find_Substring_permutation(s,n+1); for( g=b.begin();b!=b.end();b++) { a.push_back(s[n]+*g); } } return a;} |
answer: In Groovy it is as simple as:def s = "ease"def results = s*.toCharArray().permutations().unique().collect { it = it.join() }def expected = [‘aees’, ‘aese’, ‘asee’, ‘eaes’, ‘ease’, ‘eeas’, ‘eesa’, ‘esae’, ‘esea’, ‘saee’, ‘seae’, ‘seea’]assert results.containsAll(expected) && results.size == expected.size |
question :
Question from director: "… four people need to cross a bridge at night, there is only one flash light and only one person can walk on the bridge at a time. How do would you get them all across the bridge?" |
answer: The first person carries the second person across on his back. The second person goes back to retrieve the third person and carries him across. The third person goes back for the fourth person and carries him across. |
answer: Nope, only 1 person at a time, remember? just have the last person shine the flashlight on the bridge while the other people cross and then cross last. |
question :
Given 2 strings find the common words along with the time and space complexity. How would you optimize the algorithm |
answer: (function(w){ var arr = w.split(" "); var dct = {} while(arr.length){ var next = arr.pop(); dct[next] ? dct[next]++ : dct[next]=1; } console.log(dct)})("cat cat hat fat hat hat hat cat nap fat") |
answer: Here is what you need: public static ArrayList<String> findCommonStrings(String s1, String s2) { ArrayList<String> result = new ArrayList<String>(); String[] words1 = s1.split("\\W"); String[] words2 = s2.split("\\W"); int words1Length = words1.length; int words2Length = words2.length; for (int i = 0; i < words1Length; i++) { if (words1[i].length() == 0) { continue; } for (int j = 0; j < words2Length; j++) { if (words2[i].length() == 0) { continue; } if (result.contains(words1[i])) { continue; } if (words1[i].equals(words2[j])) { result.add(words1[i]); } } } return result; } |
answer: To get O(N) for time complexity, you can split each string by spaces, traverse the first string and put each word into a hash, then traverse the second string of words checking each word to see if it was in the hash. Hash functions are O(1) and traversing each string is O(N), so, final time complexity is O(N). |
question :
Given two sets of trees and ignoring the content of the nodes, describe rules that would define whether or not these two trees are equivalent. |
answer: After a bit of handholding, I came up with three rules for equivalency for two trees: 1) equal # nodes, 2) equal depth and 3) # of children of parent at a particular depth; there’s probably at least one other condition I missed in this interview. |
answer: Traversing one tree and mirroring those moves on the other tree should work. Need to remember to consider the NULL nodes too, else the first tree might be a subset of the second. |
answer: bool Equivalent(Node a, Node b){ if(a == null && b == null) return true; if(a == null || b == null) return false; // since they aren’t both null, and 1 is, not equivalent return(Equivalent(a->left, b->left) && Equivalent(a->right, b->right));} |
question :
A company doesn’t want to work with Amazon because of their loyalty to one of your competitors. You’re in an elevator with that company’s CEO, how do you convince him to work with you in 30 seconds? |
answer: You can’t convince a CEO in 30 seconds. You need to instead figure out what the root issue is — is he afraid to lose revenue with your competitor, etc. You need to build a case for why the CEO should meet with you again to really dive deep. |
answer: Just the two of you in the elevator? 30 seconds? Hmmm… |
question :
Do a deep copy of a linked list in which each item, in addition to the normal "next" pointer has a random pointer to another item in the list. |
answer:
This post has been removed. Please see our |
answer: The list can be cloned with three steps:(1) It creates new nodes and clones data of the original nodes. For each node N in the original list, the cloned node N’ is linked to the original node N.(2) The second step is to set m_pSibling for each cloned node. Supposing originally the m_pSibling in the node N points to the node S. The node N’, the cloned node of N, is the next node of N, and the node S’ is also the next node of S. Therefore, it locates the m pSibling target of the node N’ in O(1) time.(3) It splits the long list into two lists in the third step. The nodes with odd indexes are linked together with m_pNext pointers, which reform the original list. The nodes with even indexes are linked together with m_pNext pointers too, and they compose the cloned list.The solution is copied from a very good book <Coding Interviews: Questions, Analysis & Solutions> |
question :
Heap Sorting. What data structure do you use to implement it? Time to access and sort. Code it. |
answer: Using an array, you know the child of a node by using the 2i+1 formula. |
answer: It depends on the size. It is better to implement it tree instead of array. |
question :
Is it possible to sort using linear time a file with lots of numbers that contain duplicates, when there are no limits of resources or space? |
answer: It is possible, just use a hash map in the first pass, and then on the second pass store it in a one dimensional array. |
answer: if space is not a problem, create a integer array with size equal to the range of numbers. initialize all to 0. Then do array[number]++ for each number in file |
answer: use bucket sort.. if stability is not the issue. or use counting sort |
question :
3. If you were to rank quality, customer satisfaction, and safety in order of importance, how would you rank them? Discuss. 4. Tell me about a time when you were faced with an unforseen problem and how did you handle it. |
answer: Safety (ALWAYS FIRST), then other 2 in any arguable order |
answer: Safety, Quality, and Productivity IN THAT ORDER is the Amazon way |
question :
Roman to Int |
answer: create a dictionary of std. roman values, parse through the roman string and match with the dictionary values — keep incrementing the output as you iterate and keep truncating the input string as you go through |
answer: Your answer is incorrect. This is how you should have done it: public static int romanToLatin(String romanNumber) throws Exception { HashMap<String, Integer> romanLetters = new HashMap<String, Integer>(); romanLetters.put("I", 1); romanLetters.put("V", 5); romanLetters.put("X", 10); romanLetters.put("L", 50); romanLetters.put("C", 100); romanLetters.put("D", 500); romanLetters.put("M", 1000); int stringLength = romanNumber.length() – 1; int result = 0; int last = 0; int sign = 1; int current; for (int i = stringLength; i >= 0; i–) { current = romanLetters.get(romanNumber.subSequence(i, i+1)); if (current > last) { result += current; sign = 1; } else if (current == last) { result += current * sign; } else { result -= current; sign = -1; } last = current; } return result; } |
question :
find if 2 strings are anagrams |
answer: hash |
answer: Hash what, lol ? :)))You simply need to alphabetically sort characters in strings and then compare the result. |
answer: think about the time complexity. Whats the time complexity of the sorting? NlogNAnd when using hash mapping, it can be only N. Mapping the string to an alphabet array, the index is the char and the value stores the frequency of the char. Hope it helps. |
answer: easiest way probably to reduce the characters to ascii, add them all together. If values are equal, they all contain the same characters. O(n) |
question :
Telephone interview: Find largest integer from an array of integers. The integers in the array are arranged in strictly increasing (no 2 integers are same) or strictly increasing then decreasing; so like a curve and you have to find the peak. Discuss time complexity. Write code. |
answer: Binary search |
answer: First, binary search will not work since just looking at a single point will not tell you if it’s on the decreasing or increasing side of the curve.What you need is modified binary search. Looking at position i check position i+1 if it’s increasing then search right otherwise search left;Code:int peak(vector<int> V, int i, int iStart, int iEnd){assert( i >= 0 && i < V.size());assert( iStart >= 0 && iStart < V.size());assert( iEnd >= 0 && iEnd < V.size());assert( iStart <= i && i <= iEnd );if (i == iEnd) return i;int iCurr = V[i];int iNext = V[i+1];int iStartNew = iStart;int iEndNew = iEndlif( iCurr < iNext ) iStartNew = i;else iEndNew = i;int iNew = (iEndNew-iStartNew)/2;if( iNew == i ) iNew++;return peak(V, iNew, iStartNew, iEndNew);} |
answer: The question is a variation of the commonly asked problem of finding the start/end index of a sorted array that has been rotated. Takes O(log n) time. |
question :
given an array of numbers to remove the duplicates |
answer: I’m not sure. Maybe use merge sort and throw away duplicate values. |
answer: Sort the array in place. Then iterate and you can easily find duplicates by comparing the current and previous values. Sort is n log n; iterate is n. Total is n log n. |
answer: That is the answer that I gave. The interviewer than asked "how do you delete the duplicates from the array."I couldn’t figure out that part. |
answer: The simplest way is to use a set (no duplicate keys, and, if values are used as keys, no duplicate values). This way you simply need to iterate over the entire array and add each key/value into the set (it ignores adding it if it’s a duplicate). |
answer: Matt, Can’t use more memory. |
answer: 1) Sort this array by using quicksort, so the time will be O(nlogn),2) Start p1 pointer at beginning, and p2 at last and start move p1++3) if found p1 == previous p1, sway p2 and previous p1, and move p2–, the idea is trying to move all duplication to the end of arrary,4) keep doing 3) till p1 = p2,5) so we have a clear array without dup, then use quicksort again from index 0 – p1 |
answer: if you want to remove duplicate element in the array, try this algo:num = 0;for (i =0; i < arr.length()-1; i++){ if (arr[i] < arr[i+1]) { arr[num++] = arr[1]; }}arr[num] = arr[n-1]; |
answer: http://stackoverflow.com/questions/1532819/algorithm-efficient-way-to-remove-duplicate-integers-from-an-array |
question :
You have two products to launch in a new country before the holiday and you have the resources to only launch one product at a time. Walk me through how you would deal with this situation. |
answer: I asked questions back to interviewer to provide more details. The more details they gave the more detailed my questions were to the point where I had enough "theoretical" information to make an informed decision. |
answer: can you provide more details on exactly what your conclusion was? E.g given what we have we have to prioritize one over the other; we have to stagger the launch; launch with only certain features, etc |
question :
My personal failure |
answer: Need to learn positve failures |
answer: What was involved in the skills test? How long did it take? Was there an IQ test? If so how long was that and what was involved? |
question :
validate a binary tree |
answer: boolean isBST(Node root) { if (root == null) { return true; } return (isBST(root.left) && (isBST(root.right) && (root.left == null || root.left.data <= root.data) && (root.right == null || root.right.data > root.data));} |
answer: binary tree is either empty (null reference), or is made of a single node, where the left and right pointers each point to a binary tree.suppose ‘BinaryTree’ is the name of the class representing the binary tree implementation.public static boolean isBinaryTree(Object obj){ if(!obj instanceof BinaryTree) return false; if(null == obj || null == obj.leftChild || obj == this.rightChild ) return true; else return obj.leftChild.isBinaryTree() && obj.rightChild.isBinaryTree();} |
answer: There is a difference between Binary tree and Binary search tree, so the interviewer question was for binary tree, so no need to check for the data, just check if each node in the tree has just left and right child. |
question :
Binary search tree find the second max |
answer:
This post has been removed. Please see our |
answer: In a binary search tree all the nodes in left sub-tree have smaller or equal key than the parent’s key and all the nodes in right sub tree have greater key than the parent node’s key.class BST{……….public int getSecondMaxKey(){ BST lastNode = null; BST secondLastNode = null; BST next = null; while(this.rightChild != null){ secondLastNode = lastNode; lastNode = this; this = this.rightChild; }return secondLastNode;}} |
answer: Second max value is simply the value of the second last node in an in-order traversal of the BST(assuming unique node values) |
question :
Tell me how you would scale a social media software platform? |
answer: I didn’t have a good answer for this one. |
answer: Its such a tricky question. I guess its by the analytic we use to know the page views and all.. |
answer: Try to define "scale", ask for clarifications. Are we trying to scale to more users or to more ad providers? Are there any current bottlenecks? What is the goal here? How about we improve the experience by providing more relevant ads? etc… |
question :
Given a trie and a prefix, find the word (in the trie) that starts with some subsequence of the prefix and also has the longest such subsequence. |
answer: was this question part of the phone interview or the actual interview? |
answer: It was part of the actual interview. |
question :
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. |
answer: public static int notRepeated(int[] given) { Map<Integer> m = new HashMap<Integer>(); 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; } }} |
answer: 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 belowsub 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);} |
answer: first sort the array.n then1)for i=1 to n { if ( element [i] !=element [i+1] ) { cout<<element[i] break } else { i=i+2 }}I dnt have any idea about its time complexity… |
answer: 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<input.length; i++) { if(input[i] != repeat) return input[i]; } } return -1;} |
answer: 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 |
answer: only 2 possible solutions1.) using sorting2.) using additional space. which will be less than o(n) |
question :
Reverse a linked list. |
answer: public static Node reverse(Node n){ if(n != null) { Node reversed.data = n.data; while(n.next != null) { Node insert; insert.data = n.next; insert.next = reversed; reversed = insert; n = n.next; } return reversed; } return null;} |
answer: A recursive approach if anyone is interested. Only works for singly linked/non circular atm.called like: reverse(head, null);public static ListNode reverse(ListNode curr, ListNode prev) { if (curr == null) { return prev; } else { ListNode temp = curr.next; curr.next = prev; prev = curr; return reverse(temp, prev); }} |
answer: Node ReverseLinkedList(Node head){ Node next = head.next; if (next == null) { return head; } Node revList = ReverseLinkedList(head.next); next.next = head; head.next = null; return revList;} |
question :
Write a function that returns the depth of a tree. |
answer: public static int depth(Node root, int level){ if(root != null) { if(depth(root.right, level + 1) > depth(root.left, level + 1)) return depth(root.right, level + 1); else return depth(root.left, level + 1); } return level;} |
answer: Slightly simplified :] (I think this works; not doubling up on the recursive calls either)public static int depth(Node root, int level) { if (root == null) return level-1; return Math.max(depth(root.right, level+1), depth(root.left, level+1));} |
answer: int finddepth(node_t* node){ if(node == NULL) return -1; else return 1 + MAX(finddepth(node->lchild), finddepth(node->rchild));} |
question :
Serialize (flatten) and de-serialize a binary tree. First describe the approach, then write the code. |
answer: I know that some people didn’t get to the de-serialization code…so it might be a bit long.The question itself is pretty basic so the objective should be to provide a clear explanation and code.Interviewer seemed happy that I didn’t jump straight to the solution, but instead inquired about any system restrictions, requirements etc. |
answer:
http://www.leetcode.com/2010/09/serializationdeserialization-of-binary.html |
answer:
For BSThttp://www.leetcode.com/2010/09/saving-binary-search-tree-to-file.html |
question :
Given a list of points in 2D and a single reference point, find k nearest neighbors. No code required (iirc). |
answer: Another fairly straight-forward question, important to consider time/complexity trade-offs.There are 2 obvious solutions and one more complicated (but more efficient one) that uses a modified search algorithm. |
answer: If the reference is fixed then take the distance between that reference and the points and use it to sort the points. O(n) to take distance, O(nlogn) to sort, O(k) to get the k largest so O(nlogn) for each reference.The other solution include putting the points into a tree to enable efficient adding of points or overlaying a grid as a heuristic. |
question :
Given a binary tree, convert it into a doubly circular linked list. The structure of the tree was given by the interviewer and also the structure of the doubly circular linked list. |
answer: The elements in the DCLL were in the same order as the inorder traversal of the binary tree. So if you know how to code the inorder traversal of a tree in any language the question won’t be that hard. |
answer: The following blog discussed how to convert a binary search tree into a double linked list:http://codercareer.blogspot.com/2011/09/interview-question-no-1-binary-search.html |
question :
Given an array A of n integers, in sorted order, and an integer x. design an O(n)-time complexity algorithm to determine whether there are 2 integers in A whose sum is exactly x. |
answer: bool is_sum_num( int num_arr[], int size, int sum){ // quicksort(num_arr, size); for (int end= size-1; end >=0; end–) { int low = 0; high = size-1; bool check_again = false; while(low<high) { if (sum = num_arr[low]+num_arr[high]) return true; if ( sum -num_arr[low]<num_arr[high] high–; if (sum-num_arr[high] > num_arr[low]) low++; } wile ( low <=high); return false;} |
answer: The above is not Software Engineering. It is Computer Science. Amazon got it wrong.Software *Engineering* these days is almost always related to COTS where an engineer researches suitable components and plugs them. Custom components may be made.A Software Engineer would therefore import some package for the above problem instead of wasting a precious time inventing from scratch. |
answer: from random import randint# Constant bounds on the random numbers generated.LOWER = 0UPPER = 100# Number of items in the array.n = 50# For this solution, the array doesn’t have to be sorted.array = [randint(LOWER, UPPER) for index in range(n)]def sum_in_array(x, array): # All of the differences are stored in a hash table; order 1 lookup. differences = {} for item in array: # If the new item is in the differences hash, then we have # a solution. if item in differences: print ‘%i + %i = %i’ % (item, differences[item], x) return True # Store the difference and continue. differences[x – item] = item return False# Test code.for index in range(10): # Arbitrarily generate a target x. x = randint(LOWER, 2*UPPER) # Check x. sum_in_array(x, array) |
answer: bool sum_to_n_unsorted(int a[],int len,int sumto){ map<int,int> diff; for(int i=0;i<len;i++) diff[a[i]]=1; for(int i=0;i<len;i++) { int df=sumto-a[i]; if(diff.find(df) !=diff.end()) return true; } return false;}bool sum_to_n_sorted(int a[],int len,int sumto){ int left=0,right=len-1; while(left<right) { int tmp=a[left]+a[right]; if(tmp==sumto) return true; if(tmp<sumto) left++; else right–; } return false;}void test_sum_to_n(){ int a[]={3,7,10,20,23}; cout << sum_to_n_unsorted(a,sizeof(a)/sizeof(int),32)<<endl; cout << sum_to_n_sorted(a,sizeof(a)/sizeof(int),32)<<endl;} |
answer: public static boolean canSumTo(int[] numbers, int target) { int i=0; int j=numbers.length-1; int sum; while (i < j) { sum = numbers[i] + numbers[j]; if (sum < target) { ++i; } else if (sum == target) { System.out.println("soln: " + numbers[i] + " " + numbers[j]); return true; } else { –j; } } return false; } public static int[] randomIntArray(int length, int maxValue) { Random random = new Random(); final int[] numbers = new int[length]; for (int i=0; i < length; ++i) { numbers[i] = random.nextInt(maxValue); } Arrays.sort(numbers); return numbers; } public static void test() { int[] numbers = new int[] { 1, 3, 5, 7 }; System.out.println("can sum to 10:" + canSumTo(numbers, 10)); int[] numbers2 = randomIntArray(10, 50); System.out.println("numbers: " + Arrays.toString(numbers2)); System.out.println("can sum to 50: " + canSumTo(numbers2, 50)); } |
question :
given a large array of int return the length of the longest increasing(non-necessarily-adjacent) sub-sequence |
answer: from random import randintfrom pprint import pprint# Constant bounds on the random numbers generated.LOWER = 0UPPER = 100# Number of items in the array.n = 10# For this solution, the array doesn’t have to be sorted.array = [randint(LOWER, UPPER) for index in range(n)]def find_subsequences(array): ”’ Returns a list containing subsequences of array. ”’ if len(array): # The current item to be sequenced and the resulting subsequences. current = array[0] results = [] # Create subsequences of everything after the current item. subsequences = find_subsequences(array[1:]) # Loop over the subsequences and compare. stored = False for subsequence in subsequences: if len(subsequence): # There are two possibilities; either the current item goes # before the subsequence, or it goes in the middle. if current < subsequence[0]: results.append([current] + subsequence) stored = True else: # Append the original subsequence. results.append(subsequence) # Check for a subsequence in the middle. for index, item in enumerate(subsequence): # Remove any duplicates. if current == item: stored = True break if current < item: results.append([current] + subsequence[index:]) stored = True # Ignore anything smaller. break # If the current wasn’t stored, then we can start a new # subsequenece. if not stored: results.append([current]) # Return the new set of subsequences. return results # The base case. return [[]]pprint(array)result = find_subsequences(array)pprint(result)print ‘Max: %i’ % max([len(item) for item in result]) |
answer: public int findLengthOfIncreasingSubsequence(int[] largeArray){ /// invalid format checking ie: null, empty /// int prev = 0; int longest = 0; int counter = 0; boolean isFirst = true; // having this is to for(int i : largeArray) { if(isFirst) { isFirst = false; counter = 1; } else { if(prev <= i){ counter++; } else { counter = 1; } } if(counter > longest){ longest = counter; } prev = i; } return longest;} |
question :
find a anagrams of given string from the paragraph. |
answer: used a hashing method. try to find it in the book "data structure and algorithm using java" |
answer: First find all permutations of given String store in hashset.Go word by word in paragraph, first check if word has same length as given String and if successful then check if word is in hashset or not. If present then print it. |
answer: public String findAnagram(String string, String paragraph){ ///////// invalid forms checking ie: null or string.length > paragraph.legth ////////////// HastMap<Character, Integer> stringCharCounter = counterCharacter(string); String[] array = paragraph.split(" "); // assuming that the paragraph consist of English characters only // also assuming that there is only one white space character in between two words. // otherwise cleaning up function may required for(String s : array){ HashMap<Character,Integer> tmpMap = countCharacter(s); if(compareHashMap(stringCharCounter,tmpMap)){ return s; } } return null;}private HashMap<Character, Integer> countCharacter(String s){ ////// invalid forms checking ///// HashMap<Character, Integer> map = new HashMap<Character, Integer>(); for(char c : s.toCharArray()){ Integer val; if((val = map.get(c)) != null){ map.put(c, val + 1); } else { map.put(c, 0); } } return map;}private boolean compareHashMap(HashMap<Character,Integer> mapOne, HashMap<Character,Integer> mapTwo) { ////// invalid forms checking ///// if(mapOne.size() != mapTwo.size()){ return false; } // we only need to check one time b/c we know that the maps are in the same size // Therefore , if there is a key that is not in both map the comparison will return false; for( Entry<Character.Integer>c : mapOne.entrySet()){ int valOne = c.getValue().intValue(); int valTwo = mapTwo.get( c.charValue() ).intValue(); if( valOne != valTwo ){ return false; } } return true;} |
question :
1.. given a number, find two numbers from an array so that the sum is equal to that number; |
answer: using hashmap, but need to consider duplicates in the array carefully |
answer: public static List<int[]> getPairsBySum(int givenSum, int[] array){ /// checks if for the array is valid /// List<int[]> pairs = new LinkedList<int[]>(); // assuming that each pair will assigned to int[0] and int[1] /// sort the array /// note that some online threads recommend to use radix sort // but this depends on how big of the integers value in the array. Therefore I won’t be doing it b/c it will make it harder to understand the code int length = array.length; int lastIndex = length – 1; for( int i = 0 ; i < length ; i++ ) { for(int j = lastIndex ; j > i; j–) { int tempSum = array[ i ] + array[ j ]; if( tempSum == givenSum ) { int[] temp = new int[] {array[ i ] , array[ j ]}; pairs.add(temp); } else if(tempSum < givenSum){ break; } } } return pairs; }} |
question :
Can you think of an example of a scenario where you would want to use a tree with more degrees of branching than a binary tree? |
answer: If you need to represent a company’s personal structure. For example, one president is trailed by more than just two vice presidents and it will span…. |
answer: Great example for this: modeling a dictionary of possible words. I.e. a->g->r works because aggregate but a->g->(g) wouldn’t because the second g wouldn’t exist in the tree (no words begin or are formed with the string "agg"). I’ve actually received this in an Amazon interview where I was asked to model the game Boggle. |
answer: B-Tree |
answer: Database indexes is a classic example |
question :
Given a string of Rs and Gs, design an algorithm to produce a string with Rs in the front and Gs after that. The number of flips from Rs to Gs or otherwise should be minimum. The number of Rs and Gs in the end need not be same as that in the beginning, however the length of the entire string should be the same. |
answer: Regarding the R&G problem… couldn’t you just scan the string keeping a count and then regurgitate the values? Essentially you could achieve an O(N) solution.for (int i = 0; i < inputString.size(); i++) { if ("R" == inputString.charAt(i)) { System.out.print("R"); else ++count;}for (int i = 0; i < count; i++) { System.out.print("G");}——–Alternatively I suppose you could swap all "R"s for 1, all "G"s for 0, calculate the binary value and then its a straight output.RGGGRRGRGGRRRR == 10001101001111 == 9039 == 8×1 = 8xR+6xG = 14char (initial length)Or am I misunderstanding the way you’ve explained the question. |
answer: How about using Merge Sort? It would be done in O(nlogn). |
question :
Delete extra spaces in a string. |
answer: This is pretty simple, i did this in couple of second yesterday, as I have requirement where i have to trim to string using Jscirptcheck this code belowI did three types of trim here Left_trim : removing whitespace from left Right _trim : removing whitespace from rightand trim function to make call of above two methodsI love using Regular expression so here are the concrete methodsString.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,"");}String.prototype.ltrim = function() { return this.replace(/^\s+/,"");}String.prototype.rtrim = function() { return this.replace(/\s+$/,"");}Here is the simple implementationfunction trim(stringToTrim) { return stringToTrim.replace(/^\s+|\s+$/g,"");}function ltrim(stringToTrim) { return stringToTrim.replace(/^\s+/,"");}function rtrim(stringToTrim) { return stringToTrim.replace(/\s+$/,"");}// example of using trim, ltrim, and rtrimvar myString = " hello my name is ";alert("*"+trim(myString)+"*");alert("*"+ltrim(myString)+"*");alert("*"+rtrim(myString)+"*");Now little more advance or i should say optimized implementationfunction ltrim(str) { for(var k = 0; k < str.length && isWhitespace(str.charAt(k)); k++); return str.substring(k, str.length);}function rtrim(str) { for(var j=str.length-1; j>=0 && isWhitespace(str.charAt(j)) ; j–) ; return str.substring(0,j+1);}function trim(str) { return ltrim(rtrim(str));}function isWhitespace(charToCheck) { var whitespaceChars = " \t\n\r\f"; return (whitespaceChars.indexOf(charToCheck) != -1);} |
answer: JavaString removeSpaces(String s){ StringBuffer sb = new StringBuffer(); for(int index = 0; index < s.length(); index++){ if(!s.charAt(index) == ‘ ‘){ sb.append(s.charAt(index)+""); } } return sb.toString();} |
question :
If you have two SQL database tables that are not joined together, how would you create another table to join them. |
answer: Pretty simple questionLets say we have two tables Person and Other school – each person is student in the school, since you need to join those two tables, you need common column to share and hence forth you find the key to join.Inner Join – join table to bring records common in both the tablesOuter Join – Bring results besides the ones that are common or rather bring distingushed results (uncommon) in two tablesI’ll write here inner join using MS- SQLQuestion has three part – create another table , join the reults and then populate the reults– Create the resulting tableCreate Table Result{string name;}– Join to table and insert into result table- Assuing two table person and school has common column nameINSERT INTO RESULTS –whatever be the join result will populate the result tableselect namefrom PersonInner join School — used inner join hereON person.Name= School.Name — used the key to join– now lets pull up the results by querying resut tableSelect Name from Result — Questions resolved |
answer: create new table mean that -> the tables are not connected, they don’t have a common column but they complete each other. they have many to many relationship mean that new table will have 2 columns (this is one option ), and the both are they primary keys of both tables, so they will be presenting the both tables, and they will be primary keys and foreign key for the connecting_tables at the same time. so table 1 and table 2 are called the look up tables and the connection_table called the bridge table.so the sql code will look something like that :create table connecting_tables(id_toPresent_1st_table int(12) NOT NULL, // the variable type and length should be the identical to the variable type and length of the primary key in the 1st tableid_toPresent_2st_table int(12) NOT NULL, // the variable type and length should be the identical to the variable type and length of the primary key in the 2st table//both are primary keys.PRIMARY KEY(id_toPresent_1st_table, id_toPresent_2st_table),//both are foreign keys.CONSTRAINT fk_table_1 FOREIGN KEY (id_toPresent_1st_table_Id) REFERENCES table_1(table_1_Id),CONSTRAINT fk_table_2 FOREIGN KEY (id_toPresent_2st_table_Id) REFERENCES table_2(table_2_Id)); |
question :
Write an inner join between two tables. |
answer: MS-SQLlets assume two tables – City and State each having common column called populationhere is the join on population fieldSelect * from CityInner join StateON city.population = state.populationDone |
answer: MS-SQLlets assume two tables – City and State each having common column called populationhere is the join on population fieldSelect * from CityInner join StateON city.population = state.populationDone |
answer: another answer.select * from table_A a, table_B awhere a.population = b.population;pick one old or new school |
question :
Read in a stream of numbers, print out the ones that are repeated an odd number of times. |
answer: 1. Initialize set S = {}2. Read a number from the stream.3. If number is not in S, add it to S. If number is in S, remove number from S.4. At any given time, the set S will have odd numbers of repeating numbers from the stream. |
answer: Might be faster to use a hash table with bit value or a bit set to do this. |
question :
Given an integer set of numbers, print all the subsets. For some reason the interviewer asked to print the supersets, but what he means is subsets. |
answer: I could not answer this one question (1st question of 2nd phone interview), he did not give any hints, just waited till I struggled for 15 minutes and ended the interview. Did not get next call. |
answer: void print_subsets(int numbers[], int num_of_numbers) { int pow_of_num = pow(2, num_of_numbers); int i;} |
answer: #include<iostream>#include<math.h>using namespace std;void print_subsets(int numbers[], int num_of_numbers) { int pow_of_num = pow(2.0, num_of_numbers); int i; for (i = 1; i < pow_of_num; ++i) { int j = i; int digit = 0; while (j != 0) { if (j % 2) { cout << numbers[digit] << endl; } ++digit; j /= 2; // This can also be done by bitwise operation } cout << "===============" << endl; }}void print_subsets_test_drive() { int numbers[] = {1, 2, 3, 4, 5}; print_subsets(numbers, 5);}int main() { print_subsets_test_drive(); return 0;}Output:1===============2===============12===============3===============13===============23===============123===============4===============14===============24===============124===============34===============134===============234===============1234===============5===============15===============25===============125===============35===============135===============235===============1235===============45===============145===============245===============1245===============345===============1345===============2345===============12345=============== |
answer: How about using recursive to solve the problem?There are two base cases:1. if array.length = 1, then the subset is itself2. if array.length = 2, then the subsets are 3, {element1}, {element2} and {element1, element2}For a array with length > 2, then the subsets are:{element1}subsets(subarray(element2, …, elementN)){element1, subsets(subarray(element2, …, elementN ))} |
answer: Thanks MGhost, trying to completely understand your solution took me some time but helped me clarify a bunch of stuff with sets and stuff. Thanks man. |
answer: Can you please explain the logic? |
answer: MGhost Nice Solution |
question :
Hasp map concepts theory questions coding question : Program to check if binary tree is a BST Complexity of the module written |
answer: checking the value of node with its children every level, pointed the disadvantage of the solution and gave me a hint.Solution: In-order traversal |
answer: Do In-Order Traversal Check if it is sorted in ascending order, if yes then the tree is BST.Time Complexity: O(n) |
question :
Normalization questions coding question: Program to find the element occurring odd number of times in an array Complexity |
answer: ended the interview 15 min earlier and asked me to mail the solution. |
answer: Just scan the array and XOR(^) the elements..the result is the element which occurs odd number of times |
question :
Say you were running an A/B test for an email campaign, what would you want to know? |
answer: REALLY? How about some background info like, WHY are we running this test, WHAT are the goals of it, WHAT is the target demographic, WHAT is the strategy behind email programs in general. Without the basics, how can ANYONE determine what "things" to look for and/or know? |
answer: Uh, how about open rate? And total number of clicks per open on A versus B? And if there is a targeted link that they most want clicked, how did it perform in A versus B? This seems like more of a standard question just to see if you understand how the basic mass-mailing platforms work. |
question :
Complexity analysis, discussion about best solution |
answer: you should pay attention to what is being asked and how you communicate your answer. The fact of writing code in paper is quite slow and tense, as the interviewer is just waiting on the phone for you to finish.In summary, a good experience. Close to Google’s standard of interview. |
answer: Given 2 arrays of numbers and a number, find 1 number from each array that sum up to the 3rd given input:You have two arrays, array1 and array2, and you want a in array1 and b in array2 such that a + b = c. The trick is to rewrite this as b = c – a. We transform each element a in array1 to c – a, then check for collisions in the two arrays. We can do this via a hash map or by sorting the two arrays and stepping through them much like in the merge part of merge sort.Python code:def main(array1, array2, c): mem = dict() for a in array1: mem[c – a] = True for b in array2: if b in mem: return c – b, b return None |
question :
How to print a link list reversely |
answer: The simplest solution would be:1. Traverse a linked list from head to tail2. During traversal, push all the elements of the node into a stack3. Once the traversal is done, pop all elements and this will print the linked list in reverse order …Looking fwd for an optimized solution … |
answer: void printLLreverse(Node *headNode){ //this is going to just iterate through the LL //add each element to a stack and //print the stack when we are finished stack <int> llStack; Node* currNode = headNode; while(currNode) { llStack.push(currNode->data); currNode = currNode->next; } while(llStack.size() > 0) { cout << llStack.top(); llStack.pop(); }} |
question :
how to get the most significant bit from a byte? |
answer: I couldnt understand what he ment by byte. I thought eight bits in binary format. But what he was asking about converting a decimal number into binary and getting the most significant bit out of it. |
answer: right shift the number by 7 positions and you get the most significant bitprintf("%d",n>>7); |
question :
how to find a number in a circularly sorted array? |
answer: public class SearchCircularSorted { public static void main(String [] args){ int a[]={8,9,10,1,2,3,4,5,6,7}; System.out.println(circularBinSearch(a,3,0,9)); } public static int circularBinSearch ( int A[],int key, int low, int high ) { if (low > high) { return -1; // not found } int mid = (low + high) / 2; int steps = 0; steps++; if (A[mid] == key) { return mid; } else if (key < A[mid]) { return ((A[low] <= A[mid]) && (A[low] > key)) ? circularBinSearch(A,key, mid + 1, high) : circularBinSearch(A,key, low, mid – 1); } else // key > A[mid] { return ((A[mid] <= A[high]) && (key > A[high])) ? circularBinSearch(A,key, low, mid – 1) : circularBinSearch(A,key, mid + 1, high); }}} |
answer: public static int IndexForNumber(int number, int[] myArray) { int offset = myArray[0]; return ((number – offset) + myArray.Length) % myArray.Length; } |
question :
Given some array such as {4, 2, 5, 3}, write a function that would take in the array and a number that would return how many pairs add up to the number. |
answer: The interviewer first asked what you would do in this situation and how you would solve the problem, and if it would be constant time, linear, or quadratic, etc. I explained the only way I could think of doing it would take quadratic time. When asked why I would be quadratic, I explained, and the interviewer explained that it would be order n squared, to which I agreed and explained that’s why I said it was quadratic. The interviewer then asked me what quadratic meant, and I said it was n squared. The interviewer said he didn’t think that was true, but he was also skeptical. The interviewer should have known the meaning of quadratic. Anyway, he then asked me what could I do if the list was sorted. He said there was a way to do this in linear time if it was sorted. This threw me off since sorting is nlogn, and then you still have to do at least n calculations. Towards the end, he threw me the hint to use a map as a way of "sorting". One mistake I made was that I assumed the numbers would be positive. |
answer: You have an array and the target number, say N. Iterate through the array and for each number n put N-n into a hashmap. Now iterate through the array again and count how many number collide with a number in the hashmap. This work because if m collides with something in the hashmap we have m = N-n for some m and n in the array, moving n to the other side we get m + n = N. |
question :
Determine if two strings are anagrams. |
answer: public static boolean isAnagram(String s1, String s2) { boolean result = false; //Basic check for the length if(s1.length()!=s2.length()) return result; char c1[]= s1.toLowerCase().toCharArray(); char c2[]= s2.toLowerCase().toCharArray(); HashMap<Character,Integer> h = new HashMap<Character,Integer>(); //Put chars from c1 in hashmap one by one. First with value as 1; then if the same letter is present as key then increment the value for (int counter = 0; counter<c1.length; counter++) { if(h.containsKey(c1[counter])) { int val = h.get(c1[counter]); h.put(c1[counter], ++val); } else h.put(c1[counter], 1); } //Remove chars from hashmap one by one as and when you encounter the chars in c2. for (int counter = 0; counter<c2.length; counter++) { if(h.containsKey(c2[counter])) { int val = h.get(c2[counter]); if(val==1) h.remove(c2[counter]); else h.put(c2[counter], –val); } else return result; } if(h.isEmpty()) result = true; return result; } |
answer: if sort(s1) == sort(s2) then its an anagram |
question :
Find the length of the longest palindrom in a given string |
answer: Only think of a n-square solution with two loops |
answer: public class LongestPalindrome { public static void main(String args[]){ String arr="aaa"; String res=""; int ptr1=0; int ptr2=arr.length(); int center=0; for(int i=0;i<arr.length()-2;i++){ center= i+1; ptr1=center-1; ptr2=center+1; while(arr.charAt(ptr1)==arr.charAt(ptr2)){ if((ptr2-ptr1)>=res.length()) res=arr.substring(ptr1,ptr2+1); if(ptr1-1>=0 && ptr2+1<=arr.length()-1) { ptr1=ptr1-1; ptr2=ptr2+1; } else break; } |
answer: you can add extra conditions to check for when the length is less than 3 |
answer: The above does not account for palindromes with an even length. Use indices as follows:center = i/2;left = center – 1;right = (i+1)/2;for(int i = 2; i < s*arr.length() – 1; i++) … |
question :
level order print a given tree |
answer: At first I use 2 queue, and the interviewer ask me to refine to using only one queue. |
answer: Take a look at any common Breadth First Search algorithm for handling tree printing. |
question :
WAP to find nth Fibonacci number. After I wrote the code, had to read it out line by line. then she asked follow up questions like why this method, what other ways you can write the algorithm, etc., |
answer: int curr = 1;int prev = 1;if (i <= 1) return 1;for (int i = 2; i <= n; i++) { int next = curr + prev; prev = curr; curr = next;} return curr; |
answer: small modification to the above program , because the fibonacci series start with 0.int fibonacci(int n){ int a = 0; int b = 1; if(n==1) return a; if(n==2) return b; for(i=3;i<=n;i++){ b = a+b; a = b-a; } return b;} |
question :
Create a Queue using two Stacks. |
answer: There was no coding required, only showing/drawing how it would work and describe its algorithmic complexity. |
answer: The solution uses two operationswap() which swaps the top elements in both stacksmove(0 or 1) if it’s 0 them moves top item from stack 0 to stack 1 and vice versaGiven stack S0 and S1move(0)=push(S1, pop(S0))swap() =x = pop(S0)push(S0,pop(S1))push(S1,x)So the solution is to repeat swap and move. By induction, a 1 item stack is already a queue. Given this works for i, here is how it would work for i+1 (to make this example simple I will show it for i=4)Since it works for 4 then you have the following stacks:S0 S1e1e2e3e4(push new element into S0)S0 S1e5e1e2e3e4(move)S0 S1e1 e5e2e3e4(swap)S0 S1e5 e1e2e3e4(move)S0 S1e2 e5e3 e1e4(swap)S0 S1e5 e2e3 e1e4(move)S0 S1e3 e5e4 e2 e1(swap)S0 S1e5 e3e4 e2 e1(move)S0 S1e4 e5 e3 e2 e1(swap)e5 e4 e3 e2 e1(move, move, move, move)S0 S1e1e2e3e4e5 |
question :
Implement integer division |
answer: public class Solution { public void integerDivision(int num, int den){ int q=0,rem=0; while(num>=den){ num-=den; q++; } rem=num; System.out.println("Quotient "+q+" Remainder "+rem); } public static void main(String[] args) { Solution sol = new Solution(); sol.integerDivision(73, 9); }} |
answer: public static int division(int a, int b) { if (a < 0) Math.abs(a); if (b < 0) Math.abs(b); if (a > b) { int q = 1; int c = b; while ((b = b << 1) < a) { q++; } b = b >> 1; while ((a = a – b) >= c) { q++; } return q; } else { return 0; } } |
answer: Minor correction public static int division(int a, int b) { if (a < 0) a = Math.abs(a); if (b < 0) b = Math.abs(b); if (a > b) { int q = 1; int c = b; while ((b = b << 1) < a) { q++; } b = b >> 1; while ((a = a – b) >= c) { q++; } return q; } else { return 0; } } |
answer: I hope this will be helpfulint divFunc(int* num,int* den,int* rem){ int q = 1; int backupNum = *num; int backupDen = *den; while((backupDen = backupDen << 1)<backupNum) { q = q << 1; } backupDen >>=1; backupNum = backupNum – backupDen; *num = backupNum; *rem = backupNum; return q;}void divide(num,den){ int q=0,r=0; while(num>den) { q = q + divFunc(&num,&den,&r); } printf("Q = %d\t R = %d\n",q,r);} |
question :
How to convert a bst to doubly linked list |
answer: One possible way is to do a in-fix traversal of the BST, and use two pointers to keep track of traversed tree nodes, in result it will be a sorted double linked list? |
answer: It’s a bit of a silly question to ask, unless there’s more info |
question :
Write a method to decide if the given binary tree is a binary search tree or not. |
answer: for binary search tree, inorder traversal should result in sorted array in the increasing order. |
answer: Further, know that the difference between the two is that a binary search tree cannot contain duplicate entries.recur down the tree – check if element is already in hashtable – – if it is, return false – – if it isnt, insert element into the hashtable – – – recur to children |
answer: I’m sorry but Anon’s answer is not correct, at least according to "Introduction to Algorithms, 3d Edition" by Cormen. The binary search tree property says that there CAN be duplicates:"Let x be a node in a binary search tree. If y is a node in the left subtree of x, then y.key <= x.key. If y is a node in the right subtree of x, then y.key >= x.key."In other words, the value of a child node may be equal to the value of a parent node, which would yield the result that "Interview Candidate" posted on Mar 14 2012. Performing an inorder tree walk would yield sorted nodes. |
answer: public static isValidBST(TreeNode root, MIN_INTEGER, MAX_INTEGER){ if (root == null) // children of leaf nodes { return true; } return root.data >= INTERGER_MIN && root.data <= INTEGER_MAX && isValidBST(root.left, INTEGER_MIN, root.data) && isValidBST(root.right, root.data, INTEGER_MAX)} |
question :
Write an algorithm/code in C to do integer multiplication and division without using multiplication nor division operators. Do the same thing for partitioned algorithm/parallelizable (suitable in parallel processing) |
answer: The simplest way:int c = a*bc = 0;if ((a==0) || (b == 0) c = 0;if (a==1) c = b;elseif (b==1) |c = aelsefor(i=0; i<b; i++) c += a;Better way is to do divide-and-conquer:pivot = b >> 1;for(i=0; i<pivot; i++) sum1 += a;for(i=pivot+1; i<b; i++) sum2 += a;sum = sum1 + sum2;With recursive D-A-C:int mult(int x, int y){ int z; if ((x==0) || (y==0)) return 0; if (x==1) return y; if (y==1) return x; z = mult(x, y>>1); if (y % 2 == 0) return z<<1; else { return x + (z<<1); }}THere are other methods, though. Anybody can answer? |
answer: Not a C Guy, but if in Java, you can do it as a method that returns for mutiplcationreturn Math.pow(10, Math.log10(a)+Math.log10(b))division:return Math.pow(10, Math.log10(a)-Math.log10(b))where a and b are the numbers |
answer: Stackoverflow has a good description of algorithm. Below is the python code. I am assuming 32 bit integerspowersof2=[2**i for i in range(32)]def multiply(a,b): result=0 for j in range(32): if (powersof2[j] & b): print powersof2[j] & b result += (a << j) return resultdef divide(a,b): result = 0 for j in range(16,-1,-1): if (b << j) <= a: result += powersof2[j] a -= (b << j) print a return result |
question :
Traverse nodes in a binary tree |
answer:
This post has been removed. Please see our |
answer: void traverse(Node node){ if(node == null) return null; System.out.println(node.data); traverse(node.left); traverse(node.right);} |
answer: It can’t be that this candidate really serves on a language committee. I find it difficult to believe that someone who serves on a language standards committee doesn’t care about the difference between an O(N^2) and an O(logN) solution, for that would be horrifying indeed. And in defense of the employee conducting the interview, if I did see a candidate that didn’t care about the difference between the two, I really wouldn’t care what they have on their resume. They could be a Turing award winner for all I would care.There’s a valid point about spatial locality, etc, but for something like N = 10^6 (for example), I’ll take even O(logN) disk reads (*gasp*), over N^2 quick register operations any day.. |
answer: Well, I do serve on language committees, two to be precise (though one is mostly in a feed forward role). And I do care about the difference between O(N^2) and O(log N)! I gave a complex answer to the interviewer because there is so much "it depends on the situation and circumstance". Other companies had interview processes which coped far better with the ambiguity, but from what I saw Amazon’s are very "by the book" black and white. Look, I interviewed for four roles within Amazon and all four interview experiences ranged between bad and truly awful, which is why I chose neither the worst nor best experience and wrote up a review of it here as representative of *my* personal experience. Some of my experiences with other Fortune 500 companies were equally awful, and there are reviews for those on here too. However, I did also have many very good interview experiences, and I begin work with one Fortune 500 company in the Fall with whom my interview experience – over 20+ hours over twelve interviewers – couldn’t have been better. Tip to interviewers: it *really* helps if you at least read the abstracts of the academic papers the interviewee has written. You could easily segment those companies which do this from those which don’t, and Amazon from my four experiences with them don’t or didn’t. |
answer: I hope you weren’t offended too much by my earlier comment. Your explanation just now puts things into better context. I have to admit that upon initially reading your original review it wasn’t very clear to me that you understood or cared about the difference between O(logN) and O(N^4). If the company was also unclear on that, you have to admit that one can see why they wouldn’t extend an offer.Of course not everything is about big-O, but you should still be able to give answers in terms of it when needed. It’s great if you know about data locality and caches, but you should still be able to show the basic analysis too. On another point, of course you should try to reuse code, but you also need to demonstrate (in an interview more than ever) that you have the skills to write new code when necessary, not by pointing them to some open source project you did, but by writing some nice, clean code for them right on the spot. A demonstration of your high skill level is more impressive than a description. It’s a proof-by-demonstration sort of culture.You might ask why anyone should re-invent the wheel, but I’ll leave you with this: if you can’t prove to them that you *can* reinvent the wheel, why would they believe you have the creativity needed to invent a motorcycle? |
answer: Wasn’t offended at all – in fact, your comment is by far the best made on this thread (as you can tell from everything else being deleted by glassdoor). And besides, caustic opinions of your opinions are part of publishing an opinion, I’m well used to it.My issue with Amazon – and it’s one shared by my buddies within Amazon too – is there is too much box ticking of standardized procedures in the recruitment process. That rewards rote pre-learning the answers to the live programming tasks you do over the telephone (search google, you’ll find precompiled cheat sheets for Amazon and indeed many of the big tech companies). That’s hardly "writing some nice, clean code for them right on the spot" as you suggest. A github repo with 40,000 lines of code stretching over a decade is much harder to fake. Amazon ought to hire on that in preference, but their recruitment process requires a standardized approach.The company I start with in the Fall used a completely unstructured process. They interview you on things that THEY don’t know anything about let alone you, and topics which have absolutely nothing to do with compsci or technology, so for example one topic was on mining copper on the Mongolian steppes. I know very little about that, and neither did they. But as the elite of the elite team (within the company) said at the start of the interview, "we’re not going to talk at all about anything to do with code during this interview. We’ll know if you’re a good hire by seeing how you think on topics both you and us know nothing about".That company offered the lowest compensation of any offers I received. But boy, what a great interview experience, so I had to accept. I hope working there is even 10% as good as they came across during the interviews. If so, I’m more than happy with lower pay.I’m no 10x programmer, maybe a 4x, so I’m not the perfect recruit. But I don’t think Amazon should have failed me on stage 1 of each of the four roles I interviewed for. Hence the review. |
answer: Mining copper on the Mongolian steppes, huh? That must be a very unique company. |
answer: They’re actually a multinational quite similar to Amazon – well known to consumers, occasionally known for moments of brilliance, otherwise fairly dull and dependable.Mining copper was one of many curve ball interview topics. Off the top of my head other topics included the technology policies of Kim Jung Il in North Korea, something about water and Tar Sands in Canada which I forget now, whether and how Russians are naturally good at science and math, how would you go about reconciling quantum physics with relativity, conflict resolution strategies between culturally disjunctive teams – and the list goes on much further (all this was many months ago now, so I’m forgetting). All this for a standard software engineering role, so I’m expected to be in a cubicle coding, not organizing world peace. Looking back on it now, it should have freaked me out much more than it did at the time. I suppose I was interviewing with so many companies at the same time it all just blurred.Anyway, we’re getting off topic from Amazon’s interview strategies. Amazon *are* a great company. They’ve soaked up the best and brightest from Microsoft particularly and it’s a much less dysfunctional working environment than Microsoft where something went wrong a long time ago, but no one can agree exactly what, and even if they could agree, top management don’t seriously think it’s a problem. However Amazon is naturally silo-ized, where the consumer goods division is quite different to consumer services which is quite different to cloud provision and even cloud reliability provision. The problem, I think, is that Amazon’s HR would prefer every engineer to be hired according to similar criteria, and that’s where this box ticking standardized list of coding exercises comes from.As a comparison, Google’s silo structure and hiring process is not dissimilar, though Google do run an elite expedited recruitment pathway which skips all the normal hoop jumping nonsense at the cost of fast tracking only those with the very best academic grades from the best US universities, or are famous. I have pretty terrible grades with a lot of bare scraping passes, none from Ivy League anything, and I’m not Dennis Richie or Rob Pike or Guido van Rossum famous. Still, it’s interesting how companies start to struggle so hard with high skilled recruitment as they get bigger. It’s not like there aren’t very good HR books on the topic, yet no one in the HRs of these big famous tech multinationals seems to ever read them (or if they do, they sure don’t implement them).I guess what I’m saying is that tech recruitment is hard, but it’s not NP hard. Just be organized and constantly reflect on your hiring system. A very good start for Amazon would be to read these reviews on Glassdoor, and proactively enact changes so they’re not failing candidates like me at stage 1 in the interview process (fail me later for lack of fit sure, but not on the initial programming exercise when I have 40k lines of open source contributions and I serve on ISO – that sort of indicates I’m not an incompetent programmer). Amazon also ought to knock some humility into some of their engineers, as a minority of them were rude and ignorant (I had one storm out during the telephone interview after giving a torrent of invective about me personally after I showed him up on a series of technical mistakes, and his colleague was clearly very embarrassed. As I said to him, "really, honestly don’t worry about it, I’ve heard far worse said about me. But you can forget me ever working for Amazon after that"). I haven’t posted a review of that interview on glassdoor because it was probably not representative of Amazon in general and the guy in question was probably just having a really bad day, though as I mentioned earlier, all four of my interviews did not go well.I just hope my review here has some effect within Amazon one day. As I said earlier, it *is* a great company. |
answer: I agree with you. You have to focus on the person’s ability to find answers not re-invent the wheel. If I were interviewing someone…as long as he can google a problem take me to an answer which perfectly fits the needs and then explain the solution (instead of blindly copying/pasting it) to me clearly, that would be the perfect candidate for the job.These kind of questions are only suitable for fresh out of college grads not people who have been in the industry for a long time. |
answer: @NikB: Thanks for the comment. Certainly when I’ve been interviewing others, I’m generally fairly shocked at how awful the average candidate is – I mean, I catch an easy third who have lied on their resume and that’s with five minutes of googling (depending on the lie, if they admit it in the interview, I actually give them a pass on it because I know what it’s like to have poor grades from no name universities). About two thirds clearly have no integrity and will tell you whatever they think you want to hear, and I personally can’t have that on my own teams (I won’t veto hires for other teams on this though). About three quarters have no evidence that they seriously self-engage in continuing professional development e.g. teaching themselves new skills not directly needed for work.I would *far* prefer a poor programmer who continually self improves over a rock star programmer. I would *far* prefer a programmer who uploads even crappy non-reusable bits of personal script to github than someone who claims they have always been too busy to get round to it. It gives me extra information to evaluate that candidate. Less information = more uncertainty = much higher chance of me choosing elsewhere.A true coder codes all the time including people and social structures, and I want those on my team irrespective of skill. I agree only about half of those are willing to share their work with others, so lack of sharing does exclude a lot of worthwhile hires.But I guess we all have our personal preferences on what we think works best. Some colleagues of mine who I respect greatly think my hiring philosophy bananas! |
question :
Given a binary search tree and a number find the closest node to that number. |
answer: You just need to go on choosing left node or the right node according to the difference you get between the given number and the node in consideration |
answer: public static Node find(Node root,int x) { if(root.lchild==null&&root.rchild==null) return root; if(x==root.data) return root; if(x<root.data) { Node lfind = find(root.lchild,x); return Math.abs(lfind.data – x) > Math.abs(root.data – x) ? root : lfind; } else{ Node rfind = find(root.rchild,x); return Math.abs(rfind.data – x) > Math.abs(root.data – x) ? root : rfind; } } |
question :
Given a list of numbers and a rand(0,1) function, which returns a random integer between 0 and 1. Provide an algorithm to randomly sort the given list, based on the output of the rand() function, which should be called once for every number on the list. Code the solution in any language of your choice. |
answer: 50% of probability that if you sort two numbers – they are sorted correctly.This vaguely sounds like a modified merge sort problem to me. |
answer: When I say, I was asked to perform a random sort, there is no ‘correct’ or ‘ wrong’ sorting. Think of it as selecting a number randomly from the given list based on the output of rand(0,1). Every number should be selected only once and the order in which you select the numbers should be random. |
answer: I think they wanted a deck shuffling algorithm here. The idea is to have two arrays: shuffled and unshuffled. For each item in the unshuffeld array generate a random number and use it to calculate an index in the shuffled deck to insert the number. You can multiply the (0, 1) random number by the length for example. You can do this problem in constant space by letting the two arrays share the same memory, and have one grow into the other by swaping out nearby items every time you move an item into the shuffled array. |
question :
What are different types of memory? |
answer: Heap and Stack |
answer: +static |
question :
Given a random array with integers, find every pair that sum up to a certain number. |
answer: public static void helper(int[] a, int m){ int tmp[] = new int[m]; for(int i=0; i<a.length; i++){ if(tmp[a[i]-1] == 1){ int result = m – a[i]; System.out.println(a[i] +" "+ result); } else tmp[m-1-a[i]] = 1; } } |
answer: // find all the pairs that sum up to a given numberint* findPair(int a[], int size, int sum){ unordered_map<int, int> numMap; int *pairs = new int [size*2]; for ( int i = 0; i < size; i++ ) { numMap.insert(unordered_map<int, int>::value_type(a[i], i)); } for ( int j = 0; j < size; j++ ) { if ( numMap.find(sum-a[j]) != numMap.end() ) { pairs[2*j] = a[j]; pairs[2*j+1] = numMap.find(sum-a[j])->first; numMap.erase(a[j]); printf("%d + %d = %d\n", pairs[2*j], pairs[2*j+1], sum); } } return pairs;} |
answer: void findPairs(int[] nums, sum){ Set<Integer> numSet = new HashSet<Integer>(); for(int num : nums){ numSet.add(num); } for(int num : nums){ if(numSet.contains(sum-num){ System.out.println("Pair: "+num+" – "+(sum-num)); } }} |
answer: Badal,There is just one little improvement if you sum=30 and you have 1,20, 10 , 15. when you found that for 20 , 10 exists. You shouldn’t check for 10. This will bring down iteration size. |
question :
11 Answers Given references to roots of two binary trees, how do you short circuit determine whether the sequences of the leaf elements of both the trees are same ? The structure of two BTs may be different. Short circuit : for ex. If the very first leaf element of each tree is different, the algorithm should stop immediately returning false instead of checking all the leaf elements of both trees. |
answer: returns the next leaf which is not traversed yet in order.Also the interviewer stressed that the implementation has to be short circuit, you should not traverse any of the trees completely before checking whether the first leaf elements of both trees are same. Other wise, we can just inorder traverse each tree and put the leaf elements in queues and compare the queues. |
answer: In-order traverse both trees and use return codes to judge what to do. For example if you return -1 it means error, stop traversing and return -1 up the tree. Otherwise keep going. |
question :
given a dictionary of words sorted according to a certain order, write a function to out put this order. e.g. input {abc, fkq, bct} output:{a, f, b, k, c, q, t} |
answer: using topology sort. |
answer: I’m not so sure topological sort was the answer. The questions just asks for a function to output the input (array of words) to an array of letters.Looks like the function would be like this:Remove letter from front of each word and inserts into the list.Before inserting into the resulting list, check if there is a duplicate. If there is a duplicate, don’t add the letter.Note: if you use a Set (in Java) this takes cares of unique elements so you don’t need to check for duplicates. |
answer: And using a LinkedHashSet to preserve order (in Java )My take on it – if the question was only asking for a function and not a sorting algorithm |
question :
implement a stack with a method which can return the minimal value in the stack without remove this value. |
answer: implement a stack in which each element record the reference of the minimal value in the previous elements. (or just keep an array to record the reference. can further reduce the space by just recording the decreasing numbers) |
answer: I would have approached it like this:Implement a stack with- fields: size = size of stack, first = first node, min = min node- methods/functions: pop, push, peek, minThen as you insert each element, you update the reference to min.When you call stack.min() – you get a reference to min |
answer: It’s not sufficient just to update the min on push(0.Need to be able to "backtrack" if pop() removes that min as well. |
answer: use a second stack to track the min |
question :
Given an array and a sum, determine if any of the items add up to sum. Do a linear space solution and constant time solution. |
answer: Tell me your constant time solution, because I am too noob to figure it out |
answer: This will return a list of the two numbers that add up to the sum public List<int> GetNumbers(int sum, List<int> array) { var hashSet = new HashSet<int>(); foreach (int i in array) { if (hashSet.Contains(sum – i)) return new List<int> {i, sum – i}; hashSet.Add(i); } throw new Exception("not in here"); } |
question :
Implement a Queue using 2 Stacks |
answer: Until the first de-queue operation, keep pushing one of the stacks, say stack1, for every enqueue operation. When you encounter the first dequeue operation, then pop stack1 into stack2. Now, pop stack2, to get the dequeued element. Henceforth, on every dequeue operation, pop stack2, and on every enqueue operation, push stack1. At some point, stack2 might become empty, but this brings you back to the first stage ! |
answer: Here is an idea: public class StacksQueue<T> { private readonly Stack<T> stack1 = new Stack<T>(); private readonly Stack<T> stack2 = new Stack<T>(); private Stack<T> dequeueStack; private Stack<T> queueStack; private Stack<T> secondaryStack { get { if (object.ReferenceEquals(queueStack, stack1)) { return stack2; } else { return stack1; } } } public StacksQueue() { queueStack = stack1; } public void Queue(T item) { int count = 0; while (queueStack.Count > 0) { secondaryStack.Push(queueStack.Pop()); count++; } queueStack.Push(item); for (int i = 0; i < count; i++) { queueStack.Push(secondaryStack.Pop()); } if (dequeueStack == null) { dequeueStack = queueStack; } queueStack = secondaryStack; } public T Dequeue() { if (dequeueStack == null) { throw new InvalidOperationException("Trying to dequeue from queue which is empty"); } T result = dequeueStack.Pop(); if (object.ReferenceEquals(dequeueStack, stack1)) { dequeueStack = stack2; } else { dequeueStack = stack1; } if (dequeueStack.Count == 0) { dequeueStack = null; } return result; } } |
question :
Reverse a String eg: I am a boy ans : boy a am I |
answer: intmain(){char s[] = "I am a boy";char a[20][20];int i=0;char *result = strtok(s, " ");if (result) strcpy(a[i++], result);while (result != NULL) { result = strtok(NULL, " "); if (result) strcpy(a[i++], result); }while (i != -1) printf("%s ", a[–i]);return 0;} |
answer: Here is an idea:char *reverse_words(char *string){ char *duplicate = strdup(string); int length = strlen(duplicate); int last_non_whitespace_index = 0; int word_length = 0; for(int i = 0; i < length; i++) { if (i < length / 2) swap_char(duplicate, i, length – 1 – i); if(duplicate[i] == ‘ ‘) { word_length = i – last_non_whitespace_index; for(int j = 0; j < word_length / 2; j++) { swap_char(duplicate, last_non_whitespace_index + j, i – 1 – j); } last_non_whitespace_index = i + 1; } } return duplicate;} |
question :
Justify the suduku |
answer: write loops to test it |
answer: oh, we need to use loops? that’s very helpful. |
answer: the function can be like this(not tested):boolean test(byte[27][9] input) { for ( int i = 0; i < 27; i++) { short result = 0; for (int j=0; j<9; j++) { result |= 1<<(input[i][j]-1); if (result != 0x1ff) { return false; } } return true;} |
question :
implement a queue from stack |
answer: using two stacks. one as head of the queue, the other as the tail of the queue |
answer: Agreed – an implementationclass Queue{private: stack q; stack s;public: push(int x) { s.push(); }; int pop() { if(q.empty()) { while(x = s.pop()) q.push(); }; return q.pop(); };}; |
question :
To find and return the common node of two linked lists merged into a ‘Y’ shape. |
answer: how 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 |
answer: The two linked lists were something like: 1->2->3->4->5 and 3->4->5->6->7->8. |
answer: For a Y shaped like this: 1 -> 2 -> 3 -> 4 ->7 -> 8 -> 95 -> 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. |
answer: @kvr what if the lists are 1-2-3-4-7-8-9 and 12-13-14-5-6-8-9 |
answer: Can this be done using hash tables? Or is there anything more efficient? |
answer: 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 this1 -2 -3 -4-7-8-9 x -x -x -x -x-o12-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. |
answer: 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, return4. if list is not exhausted, go to step 2.5. return NULL |
answer: 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. |
question :
To return the ‘m’ smallest numbers from a file of ‘n’ numbers |
answer: I would first create an array holding the first m values of the file, and sort. Then, each value I read from the file, I can compare the the last (largest) value in the array. If its smaller, do a binary search to find the correct spot in the array. Insert the number and shift everything behind it back by 1. Worst case runtime will be O(n lg m) |
answer: Why cant we simply start with min=INT_MIN. Then, read first number from file, if lower, set min=that number. Seek next number and so on… We dont need to load the whole file. We will go to the disk often though. |
answer: I will create a min heap with the given numbers and extract ‘m’ minimums from the heap which will get stored into the resultant array |
answer: Anuj, Wont it take time of O((M+N)log N) |
answer: @spammer, I think it’s O(n+m*log n), since you can construct the min heap bottom-up and that only takes O(n) |
answer: Why don’t we just sort the array and return the first m numbers? Takes O(nlogn) for sorting and O(m) to return the first m numbers. |
question :
Given two sets of numbers find the elements in A that appear in B (set intersection) |
answer: Initially I suggested sorting the sets and and than iterating the sets to find matches O(nlogn) and later we discussed solving the problem using hash tables O(n). We also discussed performance of the solutions and the possible large cost of hash function. |
answer: public void setIntersection(LinkList list1, LinkList list2) { LinkList list4 = new LinkList(); Node a = list1.head; Node b = list2.head; while (a != null && b != null) { if (a.value < b.value) { a = a.next; } else if (a.value > b.value) { b = b.next; } else if (a.value == b.value){ list4.insert(a.value); a = a.next; b = b.next; } } list4.printList(); }}Assuming we are using lists and the lists are already sorted, we can iterate through the lists and compare values and whenever there is a match, we can store the values in a new list.public void setIntersection(LinkList list1, LinkList list2) { LinkList list4 = new LinkList(); Node a = list1.head; Node b = list2.head; while (a != null && b != null) { if (a.value < b.value) { a = a.next; } else if (a.value > b.value) { b = b.next; } else if (a.value == b.value){ list4.insert(a.value); a = a.next; b = b.next; } } list4.printList(); }} |
answer: Hash table, put one set of numbers as keys into the hash table, which is O(n), then use each number in the second set as key to look-up the hash table to see if the key existed or not. |
question :
How do you think Amazon may have come up with the $80 fee for the Amazon Prime membership program? – this is a classic pricing question. |
answer: This is a classic pricing question. Remember customer-centric approach – willingness to pay etc. |
answer: this is mostly an expected value question. you expect, from historic data, a certain subset of people to make so many purchases from amazon. with expedited shipping, it makes sense that those people would increase their spend through amazon for secondary items such as gifts for friends/family that need to be shipped. the $80 should at least cover the expense of shipping costs, but the increase in demand and sales from that increase should even further outweigh the cost of shipping for amazon. there is also another special subset of people that may not realize their entire $80 cost to amazon, and any difference is strictly profit. |
question :
How do you find if two values in an array sum to a given value? Make it as efficient as possible. |
answer: assume two arrays to be A and B of sizes m and n respectively.assume the given sum as S;step 1: sort array B using Quick sort /*Worst case complexity is O(nlogn)*/step 2: for (i=0 ; i<A.length; i++) /*loop runs for n times in the worst case*/ { v=S-A[i]; if(Binary_Search(B, v)) // Binary search time complexity at runtime is O(logm) return true; } return false;SO the worst case complexity is O(nlogn + O(mlogn)); |
answer: public void findValues(int[] a, int k)HashMap<Integer, Integer> map = new HashMap<Integer,Integer>();for (i=0; i < a.size(); i++) { map.put(a[i], a[i]);}for (i=0; i < a.size(); i++) { if (map.get(k-a[i]) != null ) { System.out.println(a[i] + " " + k – a[i]); }} |
question :
Write a program that reverses the words in a sentence. |
answer: I used a stack, pushing words onto it as I reached spaces. |
answer: <?php // O(n) times function reverse1($word) { $result = ""; for ($index = strlen($word)-1; $index>=0; $index–) { $result[strlen($word)-1 – $index] = $word[$index]; } return implode("", $result); } // O(n/2) times = O(n) times function reverse2($word) { $temp = ""; if(strlen($word)%2 == 1) $stop = strlen($word)/2; else $stop = strlen($word)/2-1; for ($index = 0; $index<=$stop; $index++) { $temp = $word[$index]; $word[$index] = $word[strlen($word)-1 – $index]; $word[strlen($word)-1 – $index] = $temp; } return $word; }?> |
answer:
This post has been removed. Please see our |
answer: public static String reverseSentence(String a){ StringBuilder result = new StringBuilder(); Stack<String> stack = new Stack<String>(); String[] temp; temp = a.split(" "); for (String s : temp){ stack.push(s); } while(!stack.empty()){ result.append(stack.pop() + " "); } return result.toString(); } |
question :
Write a program that sees if two binary trees are equal. |
answer: I utilized a depth-first traversal method, comparing the data within each node and recursively checking the left, then right child. |
answer: Don’t know if this works or not…<?phpclass node{ public $left; public $right; public $value; function _construct($value=null,$left=null,$right=null) { $this->value = $value; $this->left = $left; $this->right = $right; } // O(n) times inorder traversal function testEsqual($tree1,$tree2) { if($tree1->value ==null || $tree2->value==null) return false; if($tree1->value ==null && $tree2->value==null) return true; while($tree1->value!=null) { if($tree1->value == $tree2->value) { equal($tree1->left,$tree2->left); equal($tree1->right,$tree2->right); } else { return false; } } }}?> |
answer: How if we use in-order traversal? If my understanding is correct, two binary trees are equal if they contain the same elements (although at different positions in the tree) |
answer: bool AreEqual(Node* node1, Node* node2){ if( (node1 == NULL && node2 != NULL) || (node2 == NULL && node1 != NULL ) return false; if(node1 == NULL && node2 == NULL) return true; if(node1->data != node2->data) return false; return( AreEqual(node1->left, node2->left) && AreEqual( node1->right, node2->right)};int main();{AreEqual(root1, root);}; |
answer: The solution by kvr doesn’t cover a case when node1->data and node2->data are equal.An additional if is required. |
answer: fb, If if(node1->data != node2->data) is not true, what does that tell you *Is* true? |
question :
How to find non-identical numbers in a given two List in C++ & write program ( with syntax) |
answer: sort two list first,maybe use quicksort, then merge |
answer: Hash table, use all numbers in first list ask keys with a common initial value say 1, then do a individual look-up for each number in the second list, if no such key was found then this number is non-identical, if found key, then increase value to 2, finally, go through all keys in the hash table and check their value, all the keys with value 1 are non-identical, should be a O(n) algorithm |
question :
Phone interview 1: 1. Describe what a hash map/table is. Later evolved into how to deal with collisions. 2. Write the code to take an int array and return a new int array whose value at i is the product of all values in the input array except the value at i. |
answer: 1. He was specifically looking for open addressing for dealing with collisions…2. My original implementation was the brute force n^2 implementation of multiplying everything but the ith element. This was later refined to first get the product, then divide by the ith position when construction the output array. Special cases had to handle 0’s. |
answer: int left = 1; int right = 1; for (i = 0; i < n; i++) OUTPUT[i] = 1; for (i = 0; i < n; i++) { OUTPUT[i] *= left; OUTPUT[n – 1 – i] *= right; left *= arr[i]; right *= arr[n – 1 – i]; } |
answer: How about this?int arr[100] = […];val = 1;for(i=0; i < size(arr) ; i++) val *= arr[i];for(i=0;i < size(arr);i++) arr[i] = val / arr[i]; |
question :
In-House interview: 1. Given two int arrays, return a third int array that contains all values in the first int array that aren’t in the 2nd. If a value is duplicated in the first int array, only return it once in the output array. 2. Model a deck of cards |
answer: 1. Add all values from the 2nd array to a hash table. Go through the 1st array and check the hash. If it’s not in there, add it to the output array and to the hash (so it can handle the case where a value is duplicated in the first array). |
answer: Put the arrays into Set collection set1 and set2 and do set1.removeall(set2) and return set1.Set<int> mySet1 = new HashSet<int>(Arrays.asList(array1));Set<int> mySet2 = new HashSet<int>(Arrays.asList(array2));mySet1.removeAll(mySet2);return mySet1; |
question :
In-house Interview 1. Write a program to print all combinations of ascending numbers that equal an input number. 2. Given a million points on a graph, return the 100 closest to the origin |
answer: 1. The solution involves iterating from 1-n and using a recursive method call…2. Use a Heap. |
answer: seriously, i didn’t know i needed to iterate from 1-n. that helps a lot, thanks. |
question :
In House Interview 1. Write an algorithm to solve a maze 2. Standard "what’s a problem you faced and how did you solve it" type questions… |
answer: 1. Use right-hand rule and keep track of coordinates that have been visited. |
answer: dfs |
question :
Given the word "HEAD" and the word "TAIL," write code and/or describe using computer science algorithms how you would transform from the word HEAD to the word TAIL. Each change must be by only one letter, you cannot change the letter in a given position twice, and each new word must be a valid word. |
answer:
http://stackoverflow.com/questions/2205540/algorithm-to-transform-one-word-to-another-through-valid-words |
answer:
Cool – Construct a graph. Each node has a word of four letters. Adjacent nodes are all words with one letter different from this node. So, HEAD node has neighbors, READ, BEAD, DEAD, etc. DEAD’s neighbors are DEED, DEAN, etc. Once the graph is constructed, problem is one of computing path from HEAD to tail. |
question :
Given a binary tree with the usual left and right pointers on each node, and additionally a parent pointer, make an algorithm to discover the closest ancestor to 2 nodes on the tree. |
answer: Time complexity is : O(max height of binary tree)public void findCommonAncestor(Node current,int a,int b){ if(current.getKey() <a && current.getKey()<b) findCommonAncestor(current.getRight(),a,b); else if (current.getKey()>a && current.getKey()>b){ findCommonAncestor(current.getLeft(), a, b); }else{ System.out.println(" least common ancestor is "+current.getKey()); } } |
answer: analog76, your solution is not complete. |
answer: @clusterfudge,what do you mean by incomplete? Can you be more precise?.Common ancestor – first encounter of node value between a and b. Otherwise either you go left or right node. |
answer: As far as I concern it is a binary tree not binary SEARCH tree. |
answer: thanks @naipton.1) Find matching node for the first value in the tree. If the node found create a set contains all its parents till the root.2) Use postorder traversal for recording all the ancestor.3) P1 is parent, P2 is grand parent and P3 is ggparent and continue till root. V1={P1,P2,P3,P4,….root}4) Similary find all the parent of second value V2={P1,P2,P3,.root}.5) traverse both set and first matching element in both sets is lowest common ancestor. |
answer: Find height of node 1 as h1 and height of node 2 as h2 by travelling to the root. Time O(2 lg N). If h1 > h2, then move node1 by h1 – h2 and vice versa. THen, use two pointers to move one parent at a time until parent nodes are same.Complexity – O( 3 lg N) |
question :
Serialize a Binary Tree so that I can create the same tree on another machine. |
answer: Breadth-first algorithm |
answer: you shud send two lists….1.traversed in "in-order" fashion2.traversed in "pre-order" fashion |
answer: BFS is good. So, lets say we use equal length records and we use some sort of array or file structure. Lets assume for now payload is integer. let bst be such as this 1 2 34 0 5 6 0 7 0 0Serizalize it asD,2,3,D,4,0,D,5,6,,D,0,0,D,0,7,D,0,0,D,0,0 |
question :
Create a data structure to keep track of hierarchy of employees, wages etc. Some are managers, VPs etc. They need to be interlinked such that a manager is linked to all workers under him etc. A VP has different managers under him. Need way to be able to traverse this data structure and have different pay grades etc. |
answer: i flunked this one..It was some sort of weird tree…each node in the tree had to have pointers to other trees etc. More like a graph or something. |
answer: #define MAX_TEAM 20struct employee { struct employee *supervisor; struct employee *team_members[MAX_TEAM]; int pay; char *fname; char *lname;};struct employee *root;struct employee *traverse_employees(struct employee *root, char *fname, char *lname){ struct employee *tmp, *ret; int i; if (root == NULL){ fprint("No such a employee\n"); return NULL; } else if (root->fname == fname && root->lname == lname) fprint("Employee %s %s is found and the pay is %d", fname, lname, root->pay); return root; else { for (i = 0; i < MAX_TEAM; i++) { tmp = root->team_members[i]; if (tmp != NULL){ ret = traverse_employee(tmp, fname, lname); if ( ret !=NULL ){ fprint("Employee %s %s is found and the pay is %d", fname, lname, ret->pay); return ret; } } } } return NULL;} |
question :
When do you use an array versus a linked list? |
answer: Arrays are fixed in size. While linked list is dynamic.So when we don’t know the size of the content in advance then we should use Linked List. |
answer: arrays also support indexed access to any element in O(1) time. LinkedLists would be O(n).LinkedLists work well if you need FIFO or LIFO behavior. Arrays take a little more bookkeeping to support these ops. |
question :
Coding question – given a binary tree, write code to count the sum off all siblings. |
answer: Not sure if this works…<?php // O(n) times function countSiblings($tree,$sum) { if($tree->value == null) return $sum; $sum = $sum + $tree->value; countSiblings($tree->left,$sum); countSiblings($tree->right,$sum); }?> |
answer: int totalNumberOfNodes(Node root) { if(root == null) return 0; return 1 + totalNumberOfNodes(root.left) + totalNumberOfNodes(root.right);} |
answer: private int siblingCounter = 0;public int countSiblings(BinaryNode node){ if(node.element == null) { return siblingCounter; } else { siblingCounter++; if(node.right() != null) { countSiblings(BinaryNode right); } if(node.left() != null) { countSiblings(BinaryNode left); } } return siblingCounter;} |
question :
Asked to implement a function that takes an integer and returns whether or not the number had an odd or even number of 1 bits. |
answer: It started out with an ambiguous set-up so the first thing that needed to be figured out was what kind of number to be taken in. How many bits this value was. I was told to assume it was 32 bits. I mentioned that the number may be in 2’s complement, I was told to only expect unsigned integers. The solution is pretty straight forward, it only requires a for loop that counts from 0 to 31 and checks whether the integer masked with 1 is equal to 1. If it is, add one to the accumulator and shift a bit to the right. Then I was told to extend this function to work for an n bit integer. With some hints I figured out that log base 2 of a number gave you the maximum number of bits it would take to store that number so simply replace the loop that went from 0 to 31 with a loop that goes from 0 to log_2(n). |
answer: If the task is only for positive numbers, then my solution would be:bool is_odd_set_bits(unsigned number){ bool result = false; int n = number; do { result |= ((n % 2) == 1); n /= 2; } while ((n / 2) != 0); return result;} |
answer: <?php // O(log2(n)) times function evenOrodd($num) { $result=0; while($num!=0) { if($num%2==1) $result++; $num = $num/2; } return ($result%2==1)?"odd" : "even"; }?> |
answer: mod and div operators are good, but you could set yourself apart by using a more efficient algorithm. In terms of big O, it will be the same, but it will have a higher throughput since the operations are slightly faster.<<Modifying Tim’s base code>>bool is_odd_set_bits(unsigned number){ bool result = false; int n = number; while(n != 0) { result |= ((n & 0x01) == 1); n >> 1; } return result;}masking is faster than a mod operator, and bit shifting is faster than divisions |
answer: i was trying this in java and found kinda small bug… so we should return false if the number is 3 which is 0000000011.I guess changing the line to:result ^= ((n & 0x01) == 1);will do the job… |
answer: PC, your solution is incorrect. It will always return true if the number has at least one set bit. |
question :
First explain what a tree, then binary tree, then a binary search tree is. Now implement a function that verifies whether a binary tree is a valid binary search tree. |
answer: Sadly I ran out of time for this question. But I e-mailed the response after my time was up. First create a small implementation of a binary tree, I did it in java with the standard implementation Nodes with left and right children as data points. Check whether the left child and right child have valid values, which is to say make sure all children on the right of a node have values greater than parents that they came from. The key thing that I missed during the interview was the fact that if you traverse once to the right, then once to the left, you have to make sure the value is between the max and min that you’ve encountered up to that point. |
answer: int validate_BST(struct tnode *tree){ int ret1, ret2; if (tree == NULL) return 1; else { if (tree->left != NULL){ if (tree->data > tree-left->data){ ret1 = validate_BSR(tree->left); } else return 0; } if (tree->right != NULL) { if (tree->data < tree->right->data){ ret2 = vaidate_BSD(tree->right); } else return 0; } return (ret1 == 1 && ret2 == 1)? 1: 0; } return 0;} |
answer: To find whether a binary tree is valid Binary search tree, do inorder traversal and check if the nodes are sorted. |
answer: private boolean isBST(){ return isBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } private boolean isBST(Node node, int min, int max){ if(node == null) return true; if(node.data < min || node.data > max) return false; else return (isBST(node.left, min, node.data) && isBST(node.right, node.data+1, max)); } |
answer: In order to verify the Binary Search Tree, Read the nodes in Inorder mode. Also at every step check if the current node value is less than the one previously found then exit the traversal as the items are not sorted. |
question :
Array of integers. Store duplicates in the order of their first occurrence. |
answer: Temp hash table with counts, on the 2nd loop check hash and get duplicates. |
answer: Use a set to store the number which are already seen. So whenever we get the next number, check if it is in the set.If we want to print the number only once even if it repeats multiple times, we should have another set which would have the elements already printed for being repeated. |
question :
Was given a set of fields. Was asked to figure out the best data structure to store this data in the form of a list and at any given point, retrieve the first 5 (decreasing order) of field values. |
answer: this is a Priority queue question. If a list has to be used, then use linked list.loop, if current value to insert greater than the header value or if list size less than 5, insert the currrent value, if list size > 5 remove header value. At the end return the list values in reverse order. |
answer: It is a heap come on easy question |
question :
Which sorting algorithm would be good for sorting small-sized integer arrays and why? What is the performance? What about for large-sized integer arrays? |
answer: for sorting small-sized integer arrays, i think should use Counting sort, it’s faster. the performace is O(N+k) |
answer: for large-sized integer arrays, should use bucket sort |
answer: wqj: bucket sort and counting sort don’t rely on the size of the array, but rather the range of integers in the range. Counting sort is O(n) but if it’s a 10 element array with the smallest value = 1 and the largest = 1000000, then you will use a 1000000 element temp array. Bucket is also roughly O(n), but if that same 10 element array is between 1 – 4 with repeats, you will get a lot of collisions, and the secondary sorting algorithm can be slow. |
answer: Small: Insertion SortLarge: Tim Sort or some other variation of n log n sort that switches to Insertion Sort when depth is too high / short subarray. |
question :
Give pseudocode over phone and code on a shared screen how to scramble an array of integers in random order. Then optimize it for better performance. |
answer: int[] arraycard = new int[num]; i = 0; for (i = 0; i < num; i++) arraycard[i] = i; Random randomInt = new Random(); int t; for (j = 0; j < num; j++) { int rand1 = j + randomInt.nextInt(num – j); t = arraycard[j]; arraycard[j] = arraycard[rand1]; arraycard[rand1] = t; } |
answer: The above method is the most common solution to this problem, and it is incorrect. There is a huge probability that several cards will remain in the exact same place. What you want to do is take cards out, one by one, out of the unshuffled array and insert them in a random position into a shuffled array. |
answer: This solution generates a random ordering of the numbers with probabilty 1/n that any value ends up in any specific index: public static void swapValues(int[] array, int idx1, int idx2) { int temp = array[idx1]; array[idx1] = array[idx2]; array[idx2] = temp; } public static void randomizeArray(int[] array) { Random random = new Random(); for (int i = array.length – 1; i >= 0; i–) { // get a random index in the array from {0, 1, …, i } int idx = random.nextInt(i + 1); // move the value at the index to the end of the array swapValues(array, idx, i); } } |
question :
"Solve a maze", you have a 2D matrix with 1’s as blocked and 0’s as path. Find a path from one corner to another, backtracking should be allowed. |
answer: Might be a little sloppy, but it works. public static int solveMaze(int[][] maze, int i, int j, int oldi, int oldj) { int solved = 0; if((i+1) == maze.length && (j+1) == maze[i].length) { return 1; } if((j-1) >= 0 && (j-1) != oldj && maze[i][j-1] == 0) { solved = solveMaze(maze, i, j-1, i, j); } if(solved != 1 && (i-1) >= 0 && (i-1) != oldi && maze[i-1][j] == 0) { solved = solveMaze(maze, i-1, j, i, j); } if(solved != 1 && (j+1) < maze[i].length && (j+1) != oldj && maze[i][j+1] == 0) { solved = solveMaze(maze, i, j+1, i, j); } if(solved != 1 && (i+1) < maze.length && (i+1) != oldi && maze[i+1][j] == 0) { solved = solveMaze(maze, i+1, j, i, j); } return solved; } |
answer: Here is the maze. 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 1 0 0 0 0 0 0 1 0 0 1 0 1 0 1 1 1 1 0 1 1 1 1 0 1 0 0 0 0 1 0 1 1 0 0 0 0 1 1 1 0 1 0 1 1 1 1 1 0 1 F 1 0 1 0 1 1 0 0 1 0 1 0 1 0 1 0 1 1 1 0 1 0 1 0 1 0 1 0 1 1 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 1 1 0 1 1 1 0 1 1 0 0 0 0 0 0 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1public class MazePath { char[][] maze = new char[12][12]; Queue<Node> queue = new LinkedList<Node>(); // Define the starting point and endpoint in a node. Node startingPoint = new Node(1,1); Node endPoint = new Node(10,10); Map<Node,Node> hm = new HashMap<Node,Node>(); public void createArray() throws IOException{ // read maze from a file and create an array FileInputStream in = new FileInputStream("c:/Personal/Maze.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String strLine; for(int j = 0; j<maze.length; j++) { maze[j] = br.readLine().replaceAll(" ", "").toCharArray(); } System.out.println(maze[2][0]); } public void findPathBreadthFirt(){ queue.add(startingPoint); hm.put(startingPoint, startingPoint); while(!queue.isEmpty()){ Node n = queue.poll(); if(n.equals(endPoint)){ printPathUsingParent(n); break; } addAdjacentVertices(n); } } public void printPathUsingParent(Node destination){ Node current = destination; while(current.parentNode!=null){ System.out.println(current.toString()); current = current.parentNode; } System.out.println(current.toString()); } public void addAdjacentVertices(Node v){ Node v1 =v; int row = v1.row; int column=v1.column; boolean added =false; //check if any point exist in the top side and add it in the Queue if(v1.row!=0 ){ if(convertCharToInt(maze[row-1][column])==0 ){ Node top = new Node(row-1,column); if(!hm.containsKey(top)){ addIntoMapAndStack(top,v); added=true; } } } // check point in the bottom and add it int he queue if(v1.row!=maze.length){ if(convertCharToInt(maze[row+1][column])==0){ Node bottom = new Node(row+1,column); if(!hm.containsKey(bottom)){ addIntoMapAndStack(bottom,v); added=true; } } } // check point in the right and add if(v1.column!=maze[1].length){ if(convertCharToInt(maze[row][column+1])==0){ Node right = new Node(row,column+1); if(!hm.containsKey(right)){ addIntoMapAndStack(right,v); added=true; } } } // check point in the left and add. if(v1.column!=0){ if(convertCharToInt(maze[row][column-1])==0){ Node left = new Node(row,column-1); if(!hm.containsKey(left)){ addIntoMapAndStack(left,v); added=true; } } } } public int convertCharToInt(char c){ return Character.getNumericValue(c); } public void addIntoMapAndStack(Node v,Node parentNode){ v.setParentNode(parentNode); stack.add(v); queue.add(v); hm.put(v, v); } public static void main(String [] args) throws IOException { MazePath mp = new MazePath(); mp.createArray(); // mp.findPathDepthFirt(); mp.findPathBreadthFirt(); } } |
answer: My previous answer was an implementation and here brief description on the implementation. * 1) Read a maze from file and convert into a int[][] array. * 2) Declare starting point and end point * 3) declare Queue and add startingPoint in that queue. * 4) Deque the node from Queue and find all the possible path add it in the queue again. * 5) Each Node contains a reference to their parent Node. Starting point doesn’t contains any reference to the parent node. * 6) While dequeing a node, if it matches with endpoint then traverse back to the starting point and that’s the path of the maze. * 7) To avoid duplicate traversing, create a visited=true flag or use HashMap. * * queue.add(startingPoint); * hm.put(startingPoint, startingPoint); while(!queue.isEmpty()){ Node n = queue.poll(); if(n.equals(endPoint)){ printPathUsingParent(n); break; } addAdjacentVertices(n); } */ |
answer: Here is a concept that may works, starting from the beginning point, each step could lead to possibly three path, we can draw a tree which each node has three children (max), then find the longest path would do it, each dead end will determine if the current node has any child or not. |
answer: enter the maze into a graph data structure where adjacent 0’s are connected to each other with an edge. Label the starting and ending points, and do a DFS from the starting location.This would be an internal solution, as there would be no visual representation of it, but you could easily enough attach coordinates to each node to allow for a visual solution |
answer: A* AlgorithmWikipedia has a nice animated image to describe it |
question :
Given a customer order of N items, design and implement a class that will most efficiently by space place the order in various size boxes |
answer: Create a multimap (a hash map where you can have duplicate keys). The key will be each type of box. The values will be the size remaining in the boxes after they have been filled with something. If the space left is smaller than the largest customer item, remove it from map. If there is space, fill the box, recalculate remaing space, and updte value in map. Start with smallest box key, working up to biggest boxes. If no box space can be found, get a new box, fill it, and insert in in map. |
answer: This is a famous np-hard problem. There is no polynomial optimal solution to this. Having multiple boxes and being 3D makes it very hard to implement. Finding a nice solution to put an item in a box is more than an interview question for itself. Different arrangements of items in a box will cause different amount of empty space. There is no way a candidate can come up with a good solution for this problem unless he has worked on it before.Enough to say there are hundreds of papers published for this problem. |
answer: Yes, I now realize I was at a huge disadvantage having been out of school so long and not having a Master’s degree. I have a lot of great experience and had great grades, but they didnt ask me anything about it. I just didnt have the recent theoretical background to solve this as fast as they wanted me too, but I think if they gave me another hour I would have been in the ballpark. After making lots of assumptions to simplify it, I figured it could be solved with a sorted multi-hash map or an array of sorted BST’s. But the interviewer said I ran out of time and didnt let me demonstrate my solution. I sensed he knew I was on the right track, but he cut me off. I think he was upset that I couldnt figure it out in 5 minutes. I liked the challlenge initially, but after the interview and observing overall the way they treated me overall, my personality and style would not be a fit, so all the better I didnt work for that group. |
question :
Explain how you would design and implement a asking algorithm using Java. |
answer: What is an a asking algorithm? |
answer: The interview question was "Explain how you would design and implement an algorithm for load balancing across a network using Java without the usage of a Centralized load balancing server." |
answer: add a field to the messaging for average load/latency/serving time, have each server advertise it’s load by a moving average formed over the last several transactions with clients. Have that algorithm age off old data on a sliding timebase of 10s of seconds for heavy load to 4 hours or so for a light load, such that light usage over the longest time results in the lowest load score… |
question :
"Jeff Bezos walks into your office and says you can have a million dollars to launch your best entrepreneurial idea. What is it?" |
answer: This will lead into a series of questions that probably are tailored to the job role under discussion: Who are the customers for this? How do you know there’s a market for it? How would you implement this? Why is it better than X, Y or Z? What about the risk of _____? etc, etc, etc |
answer: The answer is probably very generic. I don’t know anything about Amazon’s culture but giving your ideas, especially entrepreneurial, for no benefit to you is just not smart. Being considered for a job is equal to no benefit as Amazon has made no commitment to hire you. |
answer: Knowing the Amazon culture, the interviewer was trying to figure out if you can think big. Then, follow up questions will go into whether you can dig deep. They would question your core beliefs on things you are passionate about to determine if you can defend your position. If there are any aspects of your position that are not rock solid, they would try to provide alternate approaches to see if you are capable of disagreeing and committing to an idea other than your own. But for the most part, this is a think big check. |
answer: I would probably say a scam were you dress up as Jeff Bezos and walk into interviews a steal the interviewers best ideas and sell them as your own. It would only cost $2000 in theater dressings. That leaves $998,000 for a actual product when an idea hits me and there is a business case. |
answer: I will share as long as all parties are willing to sign a NDA. |
answer: I cannot tell you right now, I am in an interview, once I get hired we talk about it. |
answer: If I would have a good entrepreneral idea, I wouldn’t be sitting here, answering these stupid questions and waisting my time". Sure, you wouldn’t be hired, but do you want to work for the company that hiring people based on these kind of questions? |
answer: I would use it to purchase plots of land in urban areas to build stackable, self-contained pod homes for the homeless and parolees, much like I saw used for migrant construction workers in Europe. |
answer: You’re going to offer me $1 million before you even know what my idea is? |
answer: If i told you that, i would have to kill you.(i can’t say id get hired, but if i had an idea that i honestly thought i could make into something massively profitable, i wouldn’t go telling anyone about it) |
answer: It is not probably what they want to hear but the thing any sane entrepreneur when offered an investment would ask is "on what conditions?". Being offered $1M means nothing if, for example, in return Bezos wants 99% of your company. |
answer: All the good things start with faith and trust. |
answer: What office? |
answer: I would use it to create a hostile takeover of the company that makes Chapstick.The fortune I would make is from the legion of minions that follow Mr. Jeff Bezos, and the protection they would need from kissing his behind. |
answer: I would tell him my time is valuable, stop asking me what I would do with chump change. Come back with real money, when you are serious about developing my ideas. |
answer: i refuse to take the money saying that i don’t believe in partnership. |
answer: I would shake his hand, Look him in the eye, smile, and then tell him to trash the Kindle. Then I would tell him to keep the million dollars and put it into a device that would replace the tablet entirely. Next, I would tell him that I want dividend from each device produced, not sold. Million? No I would rather wait and take a billion. |
answer: It’s a million dollars. Didn’t you just say so? |
question :
Design a parking lot |
answer: A 2D array is pretty much the best data structure that I can think of for this situation |
answer: What about a hash map? |
question :
Convert a number to an array of characters without using to_s |
answer: I think the interviewer was looking for some kind of use of modular math to separate the digits out, and then assuming that the string could be represented as an array of ASCII digits. |
answer: Here’s an easy to understand version in python. Instead of chr(48 + nNum) you could just do str(nNum) but it can’t hurt to demonstrate familiarity with ASCII.def to_string(number): chars = [] while number > 0: nNum = number % 10 number /= 10 chars.append(chr(48 + nNum)) chars.reverse() return charsWhich would give something like>>> to_string(34839)[‘3′, ‘4’, ‘8’, ‘3’, ‘9’] |
question :
Write a function that takes an integer and counts the number of bits. |
answer: This is a simple bit manipulation problem. If you study before your interviews, this is a common area to study. |
answer: void count_Bits(int inp){ int count = 0; for (int y = inp; y >=1;y = y /2 ){ count++; } cout<< "number of bits : " << count<< endl;} |
question :
You are given two arrays, design a method to produce the intersection of those arrays. Analyze its runtime. |
answer: Hint: hash table. |
answer: def intersection(arr1, arr2): table = {} res = [] for i in arr1: table[i] = 1 for i in arr2: if table.has_key(i): res.append(i) return resRun time is O(n+m)–linear and space is O(n+m). Not the prettiest solution but a quick one. |
question :
Remove the nth from last element in a singularly linked list in linear time. |
answer: The general idea is to keep a pointer n elements back from the current element as you’re traversing the linked list looking for the last node. There are some edge cases when coding it. O(n) time, O(1) space. |
answer: How about? Traverse once find length. Then find n-kth element. Still linear complexity in time and 0 addl space |
answer: That works too. The first way you only traverse once though. |
question :
Given two nodes that are in a binary search tree (this is guaranteed) find the shortest traversal path between them. |
answer: I found the path to each node from the root, and stored that path in an array. The shortest path would then be the path from the end of one array (which contains a one of the nodes), up to the ‘pivot point’ of the array, and then from the ‘pivot point’ of the next array, to the node. You merge the two arrays at the ‘pivot point’ and the result is the shortest path.That was my solution. it works, but I didn’t have time to look into any special cases, debugging, optimization, etc. I’m sure there is a much simpler/efficient way.Dijkstra’s Algorithm came to mind, but I couldn’t remember it in detail off of the top of my head at that moment. |
answer:
This post has been removed. Please see our |
answer: The shortest path would be from a node to the common ancestor (of the two nodes) to the other node — right? |
answer: "The shortest path would be from a node to the common ancestor (of the two nodes) to the other node — right?"Yes, that’s correct. |
answer: while(node != null) { if (node1 < node && node2 > node) return node; else if (node1> node and node2 > node) node = node.right; else if (node1< node and node2<node ) node = node.left;} |
answer: This will do it in one scan:int path[100],pathIndex=0,found=-999;int findShortestElement(int x,int y,struct treeDef *p1){ int state=0, state_left, state_right,i; if(p1 != NULL) { if(p1->data == x || p1->data == y) { state=1; path[pathIndex++] = p1->data; } state_left=findShortestElement(x,y,p1->left); if(state_left == 1) { path[pathIndex++] = p1->data; } state_right=findShortestElement(x,y,p1->right); if( state_left == 1 && state_right == 1) { //this is LCM.. //path[pathIndex++] = p1->data; printf("Found the complete path\n"); for(i=0;i<pathIndex;i++) { printf("\t%d",path[i]); } printf("\n"); return -1; } else if(state == 1 && state_left == 1) { printf("Found the complete path\n"); for(i=0;i<pathIndex;i++) { printf("\t%d",path[i]); } printf("\n"); return -1; } else if(state == 1 && state_right == 1) { printf("Found the complete path\n"); for(i=0;i<pathIndex;i++) { printf("\t%d",path[i]); } printf("\n"); return -1; } else if(state_right == 1) { path[pathIndex++] = p1->data; return 1; } else if(state_left == 1) { return 1; } else { return state; } }} |
question :
Return the index of the first repeated character of a string. |
answer: This one was easy. Walk through string array with for loop, add each char to a java Set data structure. the add() method in a Java set returns false if the object is already in the set. When ‘false’ happens, break out of loop and return the current index. return -1 otherwise.I’m not sure if there is a way to do this without using a temporary data structure, but this is O(n) in worst case time complexity, so it’s pretty good. |
answer: public static void main(String[] args) { // Return the index of the first repeated character of a string. String s = "abdcbm"; boolean[] map = new boolean[28]; for (int i = 0; i < s.length(); i++) { if (!map[s.charAt(i) – ‘a’]) { map[s.charAt(i) – ‘a’] = true; } else { System.out.println(i); break; } } } |
answer: Well, arsh, your solution will only work for lowercase letters. |
answer: How about this?void func( char const* str){ char val = 0; for(int i = 0; i < strlen(str); i++) { mask = 1 << str[i]; if(mask & val) return i; else val |= mask; };};} |
answer: def func(str) { dict = {} l = len(str) for i in range(0,l): c = str[i] if c in dict: return dict[c] else: dict[c] = i |
answer: Oops, jumping between python and C/C++ is annoyingdef func(str) : dict = {} l = len(str) for i in range(0,l): c = str[i] if c in dict: return dict[c] else: dict[c] = i |
question :
Reverse a singly linked list |
answer: Traverse the list once to find a pointer to the tail node. Traverse the list again and insert the current node directly after the tail node you originally found. Stop when you reach the tail node. Then, set the tail to the head. |
answer: Use a stack. add each node to the stack. once you reach the tail, pop the stack and assign tail->next to the popped node. do it until stack is empty |
question :
in an array of characters find the character that is repeated the most |
answer: Priority Queue |
answer: Correct me if I’m wrong, but is priority queue really the best way? I think efficiency ends up being O(nlogn) for PQ…inserting n elements into the queue (insert is O(logn)) then peeking. Using a hash table, it takes O(n) to insert the n elements and O(n) to find the max, resulting in O(n) efficiency. |
answer: Okay actually building a heap is O(n) not O(nlogn). So both techniques take O(n). Priority queue might be a little better since it only requires one scan and peek is O(1), whereas the hash table method requires two scans through the array. |
question :
Print the BST in level order |
answer: Basic idea: perform a breadth first traversal of the tree. Every time you dequeue a node, print it. This will give a level order print in linear time. |
answer: Recursive function that starts at the root and recursively prints the value of each left and right node, along with the level order.bstprint(node, count) { if (node == null) { return; } print count + ": " + node.value; //pseudocode for printing cause lazy bstprint(node.left, count + 1); bstprint(node.right, count + 1);}bstprint(root, 0); //initial call |
answer: if not tree: return nodes=collections.deque([tree]) currentCount, nextCount = 1, 0 while len(nodes)!=0: currentNode=nodes.popleft() currentCount-=1 print currentNode.val, if currentNode.left: nodes.append(currentNode.left) nextCount+=1 if currentNode.right: nodes.append(currentNode.right) nextCount+=1 if currentCount==0: #finished printing current level print ‘\n’, currentCount, nextCount = nextCount, currentCount |
question :
What is the hardest thing in moving a team to Agile? |
answer: Not hard but varies so speak to your experience, there is not right answer for this. |
answer: Personalities and level of comfort of the development staff. Some team members can resist change they don’t understand. The key is in presentation of the core of Agile/Scrum and not in the buzzwords or trendiness – emphasize the minimized reaction to positive developments and test/missed Architecture or requirements, the daily standups being the only real hassle, etc. You pitch it to the team member’s values and sense of worth, as being an improvement to empower the coder and add worth.The next hardest thing is convincing a skeptical management, PMO, Systems Engineering staff, and probably best to not mention it to the Customer for a release or two. |
question :
What data structure would you use to find the 100 closest stars? |
answer: I would tell them:I hit use the Air Force or NASA’s DataBase because, it has been done already and no need to reinvent the wheel. The database is open to the public. |
answer: Heap |
question :
How would you reverse a doubly-linked list? |
answer:
This post has been removed. Please see our |
answer: since it is doubly linked… go through and swap the what pointers to next and last |
question :
If you have a file containing millions of integers, how would you sort the data in the file using extremely limited resources, such a s 1GB of memory? |
answer: What was the answer?In my opinion, I would answer this way:Sort each x integers (x is the number of integers that the memory can hold) then save it to the a file (n files) . Then for each file maintain a current index initiated with 0. Loop through n file and take the max integer, put it into the result file, and increase the file’s current index to one. Continue doing it till the end. |
answer: An integer is only 4 bytes! I am just saying, a million integers should consume about 4 MB of memory, and easily fit in 1 GB! So "millions" had better be closer to a quarter billion if memory is an issue.OK, to answer the intended question, I would solve it with statistics. Compute bucket ranges by using a random subset of the file, with bucket size chosen such that the expected portion of the entire file will fit within the memory available. Divide the file into these buckets, and sort the buckets individually. Concatenate the sorted buckets to create a single sorted file. |
answer: To Kurt:You missed one step. Concatenating buckets will not make a sorted list. You have to merge the buckets. However, for merging you do not necessarily have to load the whole bucket into memory. |
answer: millions is not too much , you can build a int array which have millions of cells. The array take only several mega bytes . Initialize to zero for every cell, then traverse the file and keep track of every integer by array , eg . 4789 will make array[4789]++ , this could handle duplicate number . Finally scan the array … |
answer: the interviewer is looking for the word "divide and conquer".read the n number of integers and write them in a binary tree. hold the left and right value in a datastructure which keeps track of the file an integer is written to.something like thisclass NumHolder { int min; int max; String fileName;}Map partInfo = new HashMap()for (int i=0; i<1…; i++) { int[] array = readNNumbersFromFile() sortAndWrite(array) //updates the partInfo map with NumHolder data}readFromAllPartFilesAndSaveToNewFile(partInfo)void sortAndWrite(array) { sort(array); if array[0] – array[last] > 100000 //100000 = sum number that determines how many part files will be created. writeToOtherFileToo writeToPartFile update partInfo with this write} |
answer: its called ‘external sorting’… read more on wiki… |
answer: divide the file in chunks, sort individuals chunks using quicksort and store in files. Then use merging step of merge sort on those saved files. This would be external sort. |
question :
How would you build a list of the top 100 largest elements in a file containing millions of integers? |
answer: There are several things need to be considered when answering this question. First of all, we need a space to store 100 largest integers (called G). From the number 100th on ward (called x), if x is greater than any number in S, then we need to eliminate the minimum value in S and add x to S. Therefore, the expected data structure should facilitate the extract_minimum efficiently. In my opinion, using max-heap data structure could be one of the answers. For each x we compare with the root of the heap O(1). If x > root, then extract(root) – O(logn), then insert x to the heap O(log n) again.Is there any other alternative solution? |
answer: It should actually be min heap of size 100First build min heap using 0..100 numbersAs you examine each number in the array if num > root_of_min_heap [O(1)] root_of_min_heap = num siftdown (root_of_min_heap)Output min_heap as the 100 biggest numbers |
question :
design api for cache management |
answer: looking for what kind of function u will expose with exceptions etc… |
answer: What was the answer for this?My answer would be we should apply adapter design pattern (or bridge) into this question since we could cache data using many storage engine (file, memcache, db). |
answer: From answer is Cache with Proxy patternpackage xyz;public interface Data{ public String getData();}package xyz;class RealData implements Data{ private String data; RealData(String data){ this.data = data; } public String getData(){ return data; }}package xyz;public class CacheDataProxy implements Data{ private String data = null; private RealData realData; public CacheDataProxy(){ realData = new RealData(); } public String getData(){ if(data == null){ data = realData.getData(); } return data; }} |
question :
unlimited supply of coins of different demoninations. pick min number of coins to get given amount. |
answer: standard dp algo prob |
answer: PHP solution:============<?php$amount = $argv[1];$total = 0;$coins = array();$denoms = array(‘quarter’=>25,’dime’=>10,’nickel’=>5,’penny’=>1);while ($total < $amount) { $coin = getCoin($denoms, $amount – $total); $coins[$coin]++; $total += $denoms[$coin];}print_r($coins);function getCoin($denoms,$amt) { foreach ($denoms as $name=>$value) { if ($value <= $amt) { return $name; } } throw new Exception("No denomination found less than $amt");} |
answer: // in Java int[] denom={10000,5000,2000,1000,500,100,50,25,10,5,1}; int amountInCents = 34200; int coinCount = 0; int i=0; while(amountInCents>0){ coinCount = coinCount+( amountInCents/denom[i]); amountInCents=amountInCents % denom[i]; System.out.println(amountInCents); i++; } System.out.println("min of coins is "+coinCount); |
answer: Here is the solution using dynamic programming – bottom up approach. // For denomination the answer is // The denomications are 4,3,1 . // THe rows are denominations and columns are amount. // // [[0, 1, 2, 1, 1, 2, 3, 2, 2, 3, 4, 3, 3, 4, 5], // [0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6], // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14], // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]] int[] denom={4,3,1} int n=denom.length; C = new int[n+1][amount]; for(int i=0;i<amount;i++){ C[n][i]=i; } for(int i=n-1;i>=0;i–){ for(int amt=0;amt<amount;amt++){ if(amt <denom[i]){ C[i][amt]=C[i+1][amt]; }else{ C[i][amt]=1+C[i][amt-denom[i]]; } } } |
question :
what ds can be used for LRU cache. |
answer: Queue- linked list (double) and hashtable (quick fetch). Why double linked list and not single? |
answer: PriorityQueue / LinkedHashmap are great choices in java |
question :
different between array and heap |
answer: Where are the answers? |
answer: Array: random number.Heap could be presented using array with a special way of storing elements. If a node is at nth index, its children would be stored at (2n + 1)th and (2n+2)th index. |
answer: I think what the interviewer was looking for is your understanding about heap ds. |
question :
Write a program that takes an integer and gives the closest node in a binary tree. |
answer: If we take abs(x – node.value) then the problem becomes find the min value in binary tree. |
answer: Using a normal binary tree search but keep tracks of the node that has the closest value.Node find(Node n, Value v){int gDiff = infinite;Node cNode;while( n != null){int diff = Math.abs(n.value-v);if(diff < gDiff){gDiff = diff;cN = n;}if(n.value == v){return n;}else if(n.value < v ){n = n.right;}else if(n.value > v){n = n.left;}}//end whilereturn cN;}end method |
question :
Write an algorithm to determine if 2 linked lists intersect |
answer: The first answer is simply looping through every item in list one checking it against all items in list 2 until you find a match. This is O(n2) and you’ll be asked to improve it.Think about other data structures with faster access to improve this algorithm. |
answer: ^ Use a HashMap? We could traverse and put every node we see in a hashmap |
answer: @PixelPerfect3 Yes, a hashtable would do the job. Just put every node from one of the lists into a hashtable then traverse the other list checking to see if each node exists in the hashmap.This would then be in O(n) time with the downside of using more memory for the hashtable. |
answer: I don’t understand why we would need extra space for this problem. If two linked list intersects, that means their end are the same. Traverse until the end of both list and check if the address of the last nodes are the same. |
answer: @Anonymous – you are right. All we need to do is check if the ends are the same. My solution would be useful if we want to find the node they intersect at. |
answer: @PixelPerfect3 & @Anon – Sorry guys, that’s not correct. It’s not that the end of the lists are the same – intersecting means if any nodes within the linked list are the same.For example:List 1 = 1 -> 3 -> 5 -> 6 -> 7 -> 9List 2 = 2 -> 4 -> 6 -> 8 -> 10In this case, the 4th element of list 1 and the 3rd element of list 2 are "intesecting". Notice how the ends are different yet still they intersect.The extra space used by the hashtable is made up for by the speed of lookup O(1) in the hashtable. If space is an issue and speed not, you’d go for the O(n2) solution which is to traverse through List 1 and for every node check it against all the nodes in List 2. |
answer: @Ja, would it be more clear to describe this question as "Check two LinkedLists, to see if they have one node sharing the same value." ? |
answer: @Ron Perhaps, yes. But take a look online for other people who have been asked this question from Amazon/Microsoft/Google. They tend to ask for "intersecting" linked lists, which means the lists share one or more of the same node. In my simple case above it might look as if it’s just the value of each node in the list but I think technically intersecting means they share the same node, i.e. the object.My example was just for illustration but if you were writing this for real you’d want to check the node->next pointer to see if it’s the same object in both lists. |
answer: @Ja,Your example doesn’t really make sense: how can the node with value 6 point to a node with value 7 AND a node with value 8? It can only point to one node: either 7 or 8. That’s why I think Anonymous’ answer is correct. |
answer: @PixelPerfect3 – It’s not the nodes value that’s important but the actual node itself, i.e. the value of the next pointer will be the same for a node in both lists.Simply saying "the last node in the list will be the same" is incorrect! Linked lists can intersect at any point in the lists and not share the same last node. |
answer: Actually, you know I think you guys are right after some thought! My only concern was to find the actual node they intersect at but PixelPerfect3 had a point – being that a singly linked list only points to one next node, if at any point they intersect then they must have the same node at the end of the list.Sorry for adding to the confusion. If you wish to know exactly where they intersect then my solution posted above will work but if you just need to know if they intersect, PixelPerfect3 and Anon solution of the same end element is correct. |
answer: 1) len1=find length of linkedlist12) len2 =find length of linkedlist2.3) move the bigger linked list to (len1-len2) position.4) rightnow both linked lists are equal at distance from last node. that is they are n node away last node.5) iterate both LL simulatenously and if they have same instance that is their intersection point. |
answer: I think all of you guys missed one important problem. What if the linked lists have cycles?I believe this is one of the important points the interviewer want you to think about. |
question :
Probably the most difficult question they asked me was, he put a binary tree on the whiteboard and I had to write a function that would find if the tree was symmetrical or not. Anyone who’s familiar with data structures and recursion should be fine with this, just don’t freak out when they propose the question. |
answer: Alg isSymmetric(node root): list1 = inOrderTraverse(root) list2 = list1.reverse() return list1.equals(list2)I believe this works |
answer: The above works only if the tree is balanced. So maybe check for that first before running the "isSymmetric" method. |
answer: Dont need to explain much just write four line code ..public boolean isSymetric(Node n1, Node n2) { if (n1 == null && n2 == null) return true; else if (n1 == null || n2 == null) return false; else { return (isSymetric(n1.left, n2. left) &&isSymetric(n1.right, n2.right); }} |
question :
Return top 10 most used words in a string |
answer: Go through every word, and put the count of each word in a hashmap. That will be O(n).Then for every key in the Hashmap you get it’s count and you can use different sorting algorithms to determine the order. (for example you could put everything into a heap, binary search tree, use bin sort, or use insertion sort which works fast for streaming input). |
answer: Use a queue with size 10.Then put every word into a hashmap and check its count. If it’s the max count, put it into the queue. (If this word already exists in the queue, put it at the end of the queue).Finally return the 10 words inside the queue. |
question :
Given two very large binary trees T1, with millions of nodes, and T2, with hun- dreds of nodes, create an algorithm to decide if T2 is a subtree of T1. |
answer: Perhaps I’m missing something here but I think this could be a trivial problem.You could simply do a binary search on T1 all the while looking for the root node of T2. If you find it, then T2 is a sub-tree of T1. As binary search is O(log n) this would be quite efficient too. |
answer: Ja, you got the first part right, but the second part would be to verify that T2 is exactly the same as T1 — so time would be O(log n + m) where m is the number of nodes in T2 |
answer: What Ja means is that you do not compare the node values, but the nodes themselves.In fact, the question needs to be refined, are we looking for identical trees (node values and the tree structures) or just references (addresses)? |
answer: This is a very hard problem. Look up subtree matching and you’ll see what this is about. |
answer: The first couple of posters seem to be confusing binary trees with BST. |
question :
You have a sentence that has a grammatical error, and the sentence has been broken into a parse tree. The grammatical error is because of an interaction between two words. Find the minimum complete phrase that includes the grammatical error. |
answer: Conversation was required to turn this into specific requirements – it basically boiled down to finding the nearest common parent of two nodes; sum of the parent’s leafy children would be the minimum complete phrase.My solution was first to grab the ancestors of both nodes [algorithm was written on the board], then find the lowest common one with nested loops – O(n*n). I then refined this solution to truncate the longer ancestor list (from the leaf end) and walk both from the leaf end to the grandparent until a parent matched – O(n).It seemed helpful that I pointed out that the code would fail if the nodes had no common ancestor. |
answer: Yeah, it is like finding least common ancestor. The way I would do is, I will have two stacks and from those two nodes keep pushing parents in stack till you get root. And then start poping from stack till the popped elements are different. |
question :
Given int array Sum = 10 Find number of unique integers that sum up to 10 fro that array |
answer: 2. The possible numbers are either 4,6 or 10,0 |
answer: What about 3, 7 or 2, 8 or 1, 9 |
question :
What would u do if deadline is approaching and ur product is not finished? |
answer: Guys, don’t try to pull the "I’ll work my ass off to make it work" kind of answer. Admit that its a bad situation but happens a lot. Worst solution is to add code (which introduces bugs and stuff) so say u’ll take the latest stable build, and build fail-over processes around it (auto-restart if it crashes or do regular crontab maintenance…) |
answer: Very incomplete … you might be still missing features that were important for that release. |
answer: And in most cases I’d bet you ARE going to work your ass off. But they’re trying to be polite and pretend it’s not a viable option … |
answer: And in most cases I’d bet you ARE going to work your ass off. But they’re trying to be polite and pretend it’s not a viable option … |
question :
Find k largest/smallest number in a series of numbers. What data-structures will you use? Code it on white board. |
answer: For K smallest number in series you can use a max heap of size k. When you find a new number and it is smaller than root of heap, swap it with root and heapify. |
answer: @Ajit: What’re the initial values of the max heap? What happens to the first value that comes in? |
answer: Use selection sort for ‘max’ ( or for ‘min’)If K > series.length/2 then reverse the criteria- like in stead of looking for 15th highest out of 20 element array – look for (20 -15 =) 5th lowest and so on…. |
answer: I think there’s a cool solution which involves doing a pivot operation (like quicksort) until you have the top/bottom k numbers sorted. It’s possible that you can get the top k numbers in a single pass of the array if you happen to choose a good pivot, and in general takes very few passes to find the top k numbers.I coded it up in C a while back: http://privatepaste.com/1f1df9d8f0You just call select with your list, the min index, max index, and top k numbers, respectively. It can be easily changed to find the min (just reverse the swap condition) |
question :
How would you check a BST? |
answer: public boolean checkBst(Node n) { if (n == null) return true; if (checkBst(n.left)) { if ( checkBst(n.right)) { boolean isBst = false; if (n.left != null){ isBst = n.left.data < n.data; } if (n.right != null){ isBst = n.right.data > n.data; } return isBst; } } return false;} |
answer: Looks like the prev solution needs a correction. Something like this?public boolean checkBst(Node n) { if (n == null) return true; if (checkBst(n.left)) { if ( checkBst(n.right)) { boolean isBst = 1; if (n.left != null){ isBst *= n.left.data < n.data; } if (n.right != null){ isBst *= n.right.data > n.data; } return isBst; } } return false;} |
question :
There are incoming numbers from a stream, print the largest 1000 numbers. |
answer:
This post has been removed. Please see our |
answer: Put them into a heap of size of 1000 and print it whenever u want! |
question :
Determine if two singly linked linear lists intersect. |
answer: // get last link fromLinkedList1LInk l1 = LinkedList1.getHead();while(l1.getNext()!=null){ l1=l1.getNext(); }LInk l2 = LinkedList1.getHead();while(l2.getNext()!=null){ l2=l2.getNext(); }// Check if they are same instanceif(l1==l2) " they intersectelse " they don’t intersect". |
answer: This is not what I did, I created a hashmap of the pointers of the first linked list. Then I cycled through the second linked list and saw if their were any collisions with that hashmap, if so they intersect. If I am understanding your code correctly I don’t think that would work, you need to check every pointer of the first like to every one of the second to see if they are equal. Your answer doesn’t seem to take into account different length lists etc. |
question :
"You are given an array of integers where every integer occurs an even number of times, except one integer that appears an odd number of times. Return the odd occurring integer. Write functioning code and read it to me when you’re done." |
answer: One fairly straightforward solution is to use a HashSet. As you read each element, you consider inserting it into the Hashset. If it is already in the HashSet, then you remove it (it has been considered an even number of times). If it is not already in the HashSet, then you insert it into the HashSet. Basically, the presence of an element in the HashSet keeps track of its parity. At the end, the only element in the HashSet will be the one that occurs an odd number of times. |
answer: This could be also be done w/ no extra space using quicksort.Each time doing quicksort, bring the number with the value of the pivot to the left. Then go on sort on different direction depend on the even/odd position of the pivot.Time should be O(n) n is the array lengthAs for the hashtable approach, time is O(nm), m is the unique integer numerBest case space is O(m)Correct me if I am wrong. |
answer: This could be done easily by performing a xor on all elements. The elements which are even no. of times will cancel each other and we would be left with the element that comes odd number of times. time O(n); space O(1) |
question :
judge if a tree is balanced |
answer: /* I have written this code in java. I think it workd. I have used a small test case in the main() method. Please let me know if there are any flaws. */import java.io.*;import java.lang.*;class Node { int value; Node left; Node right; Node (int value) { this.value = value; } } public class Tree { public int maxHeight(Node root) { if (root == null) return 0; else return (1 + Math.max(maxHeight(root.left), maxHeight(root.right))); } public int minHeight(Node root) { if (root == null) return 0; else return (1 + Math.min(maxHeight(root.left), maxHeight(root.right))); } public int isBalanced (Node root) { return ((Math.abs(this.maxHeight(root) – this.minHeight(root)))<=1?1:0); } public static void main(String argv[]) { Node root = new Node(0); Node child1 = new Node (1); Node child2 = new Node(2); Node child3 = new Node(3); Node child4 = new Node(4); root.left = child1; root.right = child2; child1.left = child3; child2.right = child4; Tree t = new Tree(); int n = t.isBalanced(root); System.out.println(+ n); }} |
answer: isBalanced(node) if(node->left == null && node->right == null) return true else if(node->left == null || node->right == null) return false else return isBalanced(node->left) && isBalanced(node->right)Run with : isBalanced(root) |
answer: The previous one was wrong. Here is the right one:isBalanced: if numChildren(root)!=-1 return true else return falsenumChildren(node)if node == null return 0 if numChildren(node->left) == numChildren(node->right) return numChildren(node->left)*2 +1 else return -1 |
question :
Given an array of integers A[1…n], compute the array B[1…n] such that B[k] is the product of all the elements of A, except A[k]. Part ii) Try to do it without division (some mobile devices don’t have division). Was asked to write code for part ii. |
answer: Here is a psedocode for the same.public void solveAns(){Integer a[] = {1,2,3,4,5};Integer b[5] = new Integer[5]();for ( i =0; i<5; i++){ b[i] = getProduct(a, i);}}private Integer getProduct(Integer[] a, int index){Integer prod = 1; for ( i =0; i<a.length; i+) { if ( i != index ) { prod *= a[i]; } }return prod;} |
answer: @Shilpa while your answer is correct, it is O(n^2). This can be done in O(n) with no auxillary space.Two passes of the array A :After first passB[i+1] = A1 * A2 * A3 * …. AiSo in second pass, by traversing A in reverse order and multiplying we can get the desired result. |
answer: @AV seems your method is still O(n^2)or a extra array is needed; like this:void product (int * a, int* b,int n){ int * c= new int [n]; for (int i=0;i<n;i++) { if (i==0){ b[i]=1;c[n-i-1]=1;continue;} else {b[i]=b[i-1]*a[i-1];c[n-i-1]=c[c-i]*a[c-i];} } for (int i=0;i<n;i++) b[i]*=c[i]; delete [] c;} |
answer: long Totl = 1; for ( i = 0; i < length; i++ ) // Get total product { Totl *= arry1[i]; } for ( i = 0; i < j; i++ ) { if ( arry1[i] ) prdArry[i] = Totl / arry1[i]; else prdArry[i] = 0; } |
answer: It can be almost done in O(n) time in two steps.#1. Determine the product of all numbers O(n)#2. Divide the product at its index & store it to b. Complexity O(n);For example, Let a[] = {1,2,3,4,5};//make sure doesn’t have zero.and b[] as a new array;int product=1;for(int i=0; i<a.length; i++){ product *= a[i];}for(int j=0; j<a.length; j++){ b[j] = product/a[i];}The complexity is O(2n) which is almost O(n) or theeta(n)II) Division is a collection of repeated subtraction. Instead of dividing a[i] with product, subtract a[i] with a[i] times. This’ll be O(n2). |
answer: Linear time guys.#include "stdafx.h"#include <iostream>using namespace std;void printmultipliers(int a[], int b[], int n){ int totalProduct = 1; cout << "b[] "; for(int i = 0; i < n; i++) { totalProduct *= a[i]; b[i]= totalProduct; cout << b[i] << " "; } cout << "\n"; int reverseproduct = 1; int j = n -1; while(j >= 0) { if(j == (n -1)) { cout << b[j -1] << " "; } else if(j == 0) { cout << reverseproduct; } else { cout << b[j-1] * reverseproduct<< " "; } reverseproduct *= a[j]; j–; }}int _tmain(int argc, _TCHAR* argv[]){ int a[] = {1, 2, 3, 4}; int b[4]; printmultipliers(a, b, 4); return 0;} |
question :
If I handed you a rubiks cube and told you that it had to be solved by tomorrow, how would you respond? |
answer: I got the feeling that my answer wasn’t the one they were hoping to hear, as I answered that I would gather a team to see if anyone had insight or expertise to solve it, and that if given an unrealistic time frame to solve some problem of such complexity I would shoot back to the leaders in charge of the project that it WAS unrealistic. I think they were looking for me to say that I would solve the problem at all costs. |
answer: Such questions are really stupid IMHO and I feel like punching the interviewer for asking crap like this. I don’t think such questions prove anything. A person can be really good at handling situations but not respond likewise and a pretentious person can do very well in such cases but do a horrible job when hired. Please interviewers stop with such questions! |
answer: If I were asked this question I would say, "You’ll have it today".How you do it isn’t too important, there are literally a million ways to "solve" the rubiks cube they’re handing you, it’s not a cube, it’s any problem they need solved, just get it done as soon as you can, wouldn’t you like it if you asked someone to do something & they went above & beyond? Whether it’s an inter-office request or anything else, you are always either someone’s customer or vendor & this is called "giving excellent customer service".This question is begging for Excellent Customer Service. |
answer: Anyone that asks a question of this nature is looking for a typical, corporate behind kissing answer. personally I was much more impressed with your honest answer than I would be by someone, whose nature and work ability I have no idea about, answering like someone else did on this with "You’ll have it today." You could have answered with that and have not the first clue about "customer service", because it is just a brown nosing answer.To me, a good answer is honest and forthright, and I never want to just hear what the interviewee thinks I want to hear. |
question :
You are given the head node of a binary tree. Find the height of the tree. |
answer: int FindHeight(NODE *node){ if(!node) return 0; if(node->left && node->right) return max(FindHeight(node->left)+1, FindHeight(node->right)+1); if(node->left) return FindHeight(node->left)+1; if(node->right) return FindHeight(node->right)+1;} |
answer: /* * maxDepth() computes the number of nodes from the root node * to the farthest leaf node. */int maxDepth(node *node) { if (node == NULL) return 0; else { // Compute maxdepth of each subtree. int lDepth = maxDepth(node->left); int rDepth = maxDepth(node->right); // Use the larger ones. if (lDepth > rDepth) return lDepth + 1; else return rDepth + 1; }} |
answer: with fewer variables and consice -int maxD(Node n) {if (n == null) return 0; else return 1+ Math.Max(maxD(n.left), maxD(n.right);} |
question :
Write a function atoi in C, which takes a String as input, such as "123", and outputs an int, in this case 123. |
answer: int atoi(char *input){ int length = strlen(input); int i=0; int num = 0; int sign = 1; if(input[0] == ‘-‘) { sign = -1; i++; } while(*(input+i)!=’\0′) { int digit = input[i] – ‘0’; num = num*10 + digit; i++; } return sign*num;} |
answer:
This post has been removed. Please see our |
answer: /* Converts a string to integer. */int myatoi(char *string) { int val = 0; if (string) { // Error checking to eliminate NULL string while (*string && *string <= ‘9’ && *string >= ‘0’) { val = (val * 10) + (*string – ‘0’); string++; if (*string != ‘\0′ && !(*string <= ‘9’ && *string >= ‘0’)) return 0; // Error checking to eliminate cases like ’12ABC34′ } } return val;} |
answer: int my_atoi(char *str){ int i = 0,sign=1; if(*str == ‘-‘) { sign = -1; str++; } while(*str) { i = (i<<1) + (i<<3) + (*str – ‘0’); str++; } return i*sign;} |
question :
Add two numbers represented by linked list, starting from higher digit. |
answer: First, reverse the linked list. Then add it. |
answer: use recursion |
question :
What’s hashtable? |
answer: It is not a word. |
answer: Data structure that maps a hash function to a key which inturn represents location/index in a table. this is useful for O(1) access.Usually implemented by an array. |
question :
Having to pick up n items from a warehouse find an algorithm to minimize the cost having a cost function to go from one item to another. |
answer: Shortest path algorithm, Dijkstra maybe? |
answer: Traveling Sales Man problem |
question :
The difference between and interface and an abstract class |
answer: This is pretty straight forward OO design stuff |
answer: In OOD/OOP, a "class" refers to a group (or class) of like objects. The class is where you’d find the definition of attributes, properties, methods, etc. An object on the other hand, refers to a single instance of a particular class. A common analogy I hear is that a class corresponds to say a blueprint for a house. From the blueprint you can build many houses, but each house would be an instance (or object) of that blueprint. |
answer: What is an Abstract Class?An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.What is an Interface?An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class.(source codeproject) |
question :
Using only putchar how would you print out the ascii values for each digit in an integer. For example if the integer was 123, then you would want to print the ascii values for 1, 2, and 3. |
answer: I used a recursive method involving modulus and division by 10. Not hard, just stressful writing it on paper in an interview. |
answer: void printAscii( char *input){ while(input) { putchar(*input++); }}This should work as well….printing each char as an integer would give its ascii value |
answer: Ah…the above code would just print the numbers itself not ascii valuesCould be fixed by adding ascii value of 0 charie. putchar(*input + ‘0’);input++; |
answer: void printASCII(int src) if (src > 9) { printASCII(src/10); } putchar(‘0′ + (src % 10));} |
answer: void print_ascii(int n){ while(n) { int k = (n%10)+’0′; n/=10; putchar(k); printf("\n"); }} |
question :
Given a value and an array of integers, find if there are two integers in the array that add up to the value. |
answer: Eventually they want an answer that works in O(n) time. I used an algorithm that assumed it was sorted and moved in from each side of the array checking for a match and moving the appropriate index if not. |
answer: Probably the best way to do this is to go through the array and hash them based on the value. Then you can go through the array again, take the value in the n-th position and the desired sum to find the other number that would meet the criteria and look for that number in the hash table. If the number is found, you have the answer. If not, continue iterating through the array. Requires two passes through the array, thus O(n). |
answer: There are detailed solutions for this problem:http://codercareer.blogspot.com/2011/09/no-03-maximum-sum-of-all-sub-arrays.html |
answer: public static HashMap<Integer, Integer>values = new HashMap<Integer,Integer>(); public static void findPairs(int a[], int n) { for(int i = 0; i < a.length; ++i) { if(values.containsKey(n-a[i])) values.put(n-a[i], a[i]); else values.put(a[i], null); } Iterator iterator = values.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry pairs = (Map.Entry)iterator.next(); if(pairs.getValue() != null) System.out.println(pairs.getKey() + " " + pairs.getValue()); } } |
question :
What complexity would sorting add to an array list? |
answer: O(n log n) |
answer: Depends on how efficient your sorting is. |
question :
given a sorted list of integers, how would you find whether 2 integers exist that add up to a given sum? |
answer: Here’s a fairly simple solution in C# (certainly not the most efficient, but simple).static bool sumOfTwo(int[] arr, int sum, ref int num1, ref int num2){ int len = arr.Length; if (len < 2) return false; if ((arr[len – 1] + arr[len – 2] < sum) || (arr[0] + arr[1] > sum)) return false; for (int i = 0; i < len; i++) { if (arr[i] + arr[len – 1] < sum) continue; for (int j = 0; j < len; j++) { if (i == j) continue; if (arr[i] + arr[j] == sum) { num1 = arr[i]; num2 = arr[j]; return true; } if (arr[i] + arr[j] > sum) break; } } return false;} |
answer: Have two pointers one pointing to the beginning of Array and the other pointing to the end of array. Try to traverse the first pointer forward and the second one in reverse direction.Eg:- Array –>123456789. Search for sum 91.P1 points to 1 , P2 points to 92.Add value(P1) + value(P2).Compare with 9.If the sum is equal, then these are the integersIf the sum is less, move P1 further but not P2If the sum is more, move P2 further but not P1.3.Do the step 2 till P1 is >= P2.Advantages1.This method takes good advantage of the fact that array is sorted2.You can find out multiple pairs in one iteration |
question :
A list with a set of integers. All elements appear even number of times while one appear odd number of times. Find this number that appear odd number of times |
answer: use a counter for the number of times the digit appear |
answer: Suppose a list of integers: A[1..n]We can calculate the result of A[1] xor A[2] xor ….A[n]This is the answer! |
answer: Use a HashSet. For each number in the list check to see if it exists in the HashSet. If it doesn’t, put it in the HashSet. If it’s already in the HashSet take it out. When you’ve gone through all the numbers the only number left in the HashSet will be the one that appeared an odd number of times. |
answer: 1. sort the numbers2. then do what hong sun does. |
question :
You need to design a system to provide answers to factorials for between 1 and 100. You can cache 10 numbers. How would you arrange/manage that cache, and what is the worst case for lookup on a cache miss? |
answer: cache every 10th number, starting with 5. Now, if you receive a request, calculate the answer from the closest (up OR down) cached answer, leaving you a maximum of 5 steps from a cached answer to your target. |
answer: You can’t figure out the ith fibonacci number without knowing 2 consecutive fib numbers. For example, given that the 7th fib number is 13, you wouldn’t be able to figure out the 15th, 3rd, or any other fib number. You could start back at 1 but you’d still be using low consecutive fibs.That means you can only store 5 pairs of consecutive numbers. Assuming the request for the ith fib is an even distribution from 1 to 100, store every 20th pair starting from the 20th fib number. On a miss, calculate the fib from the closest pair, which would be about 10 steps away.Now, notice that I said even distribution. I think the key to this question is to ask what the distribution of requests is. If 99% of the requests are for fib numbers 91-100, then just cache those numbers and have a cost of 90 steps for the 1% of time that you miss.Sidenote: There is an equation to approximate the ith fib number but that’s not relevant because it doesn’t require any caching. |
answer: double cachedFactorial(int value){ if (value % 10 == 5) { double cacheValue = factorialCache[value/10]; if (cacheValue == 0) { cacheValue = value * cachedFactorial(value-1); factorialCache[value/10] = cacheValue; } return cacheValue; } else if (value > 1) { return value * cachedFactorial(value-1); } return 1;}void testCachedFactorial(){ memset(factorialCache, 0, sizeof(factorialCache)); double result = cachedFactorial(100);} |
question :
Write a function to mirror a binary tree (left node to right, right to left, etc). How about very unbalance tree? |
answer: This can be done with a recursive function that traverses the tree using post order depth traversal. Once the recursive calls to the left and right subtrees return, swap the left and right pointers. The base case would be when the pointer is null.The balance of the tree doesn’t matter for this algorithm. |
answer: The function is as simple as:void mirror_node(node* n) { if (n) { node* tmp = n->left; n->left = n->right; n->right = tmp; mirror_node(n->left); mirror_node(n->right); }} |
question :
how would you trouble shoot a slow download of content on a Kindle device? |
answer: 1. Work with ATT to find out whether ATT has download issues.2. Ask Amazon IT group to see whether Amazon servers have loadbalance issues. |
answer: 0. see if you can browse the internet with normal speed1. check internet speed by speedcheck to see whether 3g or your wifi is working properly2. check amazon servers is working properly. do a cluster check so see if nodes in cluster are down or not3. see network usauge on kindle to see whether there is another process consuming too much bandwidth |
question :
The second int: You have a file like this: asb stop sba tops ….. Write the program, which prints: asb, sba stop, tops … OK, you have 100gb file – approach? Using pure java? Why you use HashTable, not HashMap? What the difference? White sort for string (you use it in the algorithm) |
answer: 1. Sort each line and use sorted word (‘abs’ for the first row) as a key for HashTable. So: ht.put(‘abs’, ‘asb); ht.put(‘abs’, ‘sba’) etc.2. This is map-reduce, we can use Hadoop etc.3. Pure java. Create file with the name ‘abs’ and write there asb, sba. The same for each key. |
answer: From your description, it looks like he’s just asking you to sort a huge file that won’t fit into memory at once. In that case, just use merge sort-like approach on the large file (I’ll call it fileIN). Read whatever of fileIN you can into memory, sort the entries in memory using quicksort and write the sorted result out to another file. Keep doing this until fileA is completely processed. Now open all of the smaller files and do a merge (i.e., look at the first entry from all the smaller files, pick the smallest, write it to fileA, and repeat until all the smaller files are empty).I’m not even sure why he asked about hashmap. |
answer: Probably my description is not good enough. One more time.We have unsorted file like this:asb….. (many other records)sba….. (many other records)stop….. (many other records)tops….. (many other records)We should read file line by line and collect all records, which use the same set of chars, somewhere, after all, for example, print it. So we should have as the result:asb, sba stop, topsasw, wsa, swabcn, cbn, nbc, cnb…..etc.The first question did not have any restrictions, after that he said the file is much more then memory we have. |
question :
In the next round, the interviewer gave me a binary tree and asked me to write all the data in a file and when the file is read back we should be able to construct the original binary tree. |
answer: This can be done by doing a preorder traversal of the tree and printing each key to the file as it is encountered. When you read the file, simply insert each key one-by-one into the new tree. They new tree will have the exact same structure as the old one. |
answer: I believe you can do something similar to a BFS where you go through each layer and print the key into the file. When reading it back we can use the formula of root index starting at 1 with the left child as 2i and the right child as 2i+1. |
answer: Can write preorder and inorder traversal. Using these two you can construct the original tree. It can also be done using postorder and inorder but it is bit tricky. So it’s safe to use preorder and inorder to reconstruct the tree. |
question :
Write a function to validate a binary tree |
answer: A tree is invalid if a node is pointed to more than once (e.g., both the left and right child point to the same node). So, traverse the tree and check for any repeats. You can check for repeats by either marking every node as you traverse it or hashing the node in a hash table. |
answer: In addition to the above, if you want to validate that the tree is a binary search tree, as opposed to just a binary tree, you would perform an inorder traversal and make sure that the keys are always increasing. |
question :
Given an array, put all repeated characters together. |
answer: simply perform the sorting according to their ASCII values. |
answer: #include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ //declare variables const int size = 2000; // N const int startRange = 97; const int endRange = 122; const int length = endRange – startRange + 1; vector<char> arr(size); vector<string> newArr(length); char ch = ‘ ‘; //initialize character array in O(N) srand(time(NULL)); for(int i = 0; i < size; i++) { arr[i] = (char) (rand() % length + startRange); } //sort array in O(Nlong(N)) sort(arr.begin(), arr.end()); //combine similar characters in O(N) for(int i = 0, j = -1; i < size; i++) { if( arr.at(i) == ch) { newArr.at(j).append(1, ch); } else { j++; ch = arr.at(i); newArr.at(j) = ch; } } for(int i = 0; i < newArr.size(); i++) { cout << newArr[i] << endl; } return 0;} |
answer: depending on the requested space complexity you don’t have to sort the chars inside the string.there are only 26 chars in the alphabet. so, you can have a map or an int array with 26 counters. each counter i will say how many times the char ‘a’ + i appears in the string.then iterate once over the string incrementing the specific counters and in the end display the map or array. |
answer: For the previous answer, you should not assume that the characters are alpha only. You should plan to have to accomodate for all possible chars, which simply means you have an array of size 256. |
question :
Find substring ‘substr’ in string ‘str’ |
answer: A brute-force substring search algorithm checks all possible positions:1 function Search(string s[1..n], string sub[1..m])2 for i from 1 to n-m+13 for j from 1 to m4 if s[i+j-1] ? sub[j]5 jump to next iteration of outer loop6 return i7 return |
answer: /** * Jun Zheng, Rice Univ * Find the start index of substring ‘substr’ in string ‘str’ * An interview question of Amazon * Java 7, running time O(m+n) * @param str * @param substr * @return */ private int substringIndex(String str, String substr){ if(str.length()<1 || substr.length()<1) return -1; if(!str.contains(substr)) return -1; int i=0; for(i=0;i<str.length();i++){ if(str.charAt(i)==substr.charAt(0)){ if(str.substring(i, substr.length()+i).equals(substr)) break; } } return i; } |
question :
Phone: reverse the letter of each word in a string! the position of the words should not be changed! |
answer: Linearly go from one side of the string to the other side and reverse each word |
answer: Have a helper function that takes in the string and two indexes denoting the start and end of a word in the string. That function will reverse the string between the given indexes.Now walk down the string. Keep track of the start of a word. When you see a space, call the helper function with the start and end index of the word. When the helper has reversed the word, repeat until the end of the string. |
question :
Given two arrays find all the points of intersection between the (i.e. equal elements) and return them in an array. |
answer: couple of solutions- sort the array (nlogn) complexity- browse with the smaller array and visit each of the bigger array and return if there is a match. Complexity (n square) thus not a good solutionnext solution- sort the arrays and remove duplicates (nlogn)- create a table, with the longer array- browse to the smaller array and update the count- |
answer: use a hashtable. O(n). |
answer: traverse first array: O(n)put elements into hashtable: O(1)traverse through second array: O(m)check for existence of element in hashtable: O(1)if yes, add to resultant array.return resultant arraySo, final time complexity is O(n) |
question :
Given a string like "I’m being interviewed by Amazon" implement a method that reverses the given string so that it looks like "Amazon by interviewed being I’m". |
answer: In java:String str = "I’m being interviewed by Amazon";String pieces[] = foo.split();String reversedFoo;for (int i = pieces.length – 1; i >= 0; i–) { reversedFoo += pieces[i]; if (i > 0) reversedFoo += " ";}System.out.println(reversedFoo); |
answer: we can first reverse the whole string, and then reverse the individual wordsO(n) complexity |
answer: /** * Jun Zheng, Rice Univ * An interview question of Amazon * Java 7, Eclipse * Reverse a sentence, e.g., "Amazon is so gay" to "gay so is Amazon" * @param str * @return */ private String reverseSentence(String str){ str=new StringBuffer(str).reverse().toString(); int j=0; for(int i=0;i<str.length();i++){ if(str.charAt(i)==’ ‘){ String s1=str.substring(j, i); s1=new StringBuffer(s1).reverse().toString(); str=new StringBuffer(str).replace(j, i, s1).toString(); j=i+1; } } String s1=str.substring(j, str.length()); s1=new StringBuffer(s1).reverse().toString(); str=new StringBuffer(str).replace(j, str.length(), s1).toString(); return str; } |
question :
Reverse a string in-place. |
answer: for(i = 0; i < strlen(str); i++){ temp = str[i]; str[i] = str[strlen(str) – 1 – i]; str[strlen(str) – 1 – i] = temp;} |
answer: @Rahul,Wouldn’t the for condition be i < strlen(str)/2?that way if you had a string of length 5, it would run for i=0 and i=1, but it wouldn’t bother doing i=2 since that is the middle element and doesn’t need switching. Without the /2, you will reverse it, then re-reverse it again.For an even length (like 6) you’d want it to do swaps on i=0, i=1, and i=2, but not i=3 |
answer: public static String reverseString(String s){ int len = s.length(); int temp = len; StringBuffer sb = new StringBuffer(); try { for(int i=1;i<len;i++){ sb.append(s.substring(temp-1,temp)); temp = temp -1; } }catch (Exception e){ System.out.println("Error: " + e); } return sb.append(s.substring(temp-1,temp)).toString(); } |
answer: void reverse(char* str){ int len = strlen(str); char* end = str + len – 1; for(char* start = str; start > end; ++start, –end ) { char ch = *start; *start = *end; *end = ch; }} |
question :
Discuss finding the most efficient route in terms of cost and time for moving products through warehouses to customers. Explain algorithm complexity. |
answer: Breadth-first traversal of a graph |
answer: shortest path algoritm |
question :
– Find k-th element from the end of the singlylinked list in single pass? |
answer: modify quick sort to get k th – element |
answer: Maintain 2 pointers front and back. back poiter will be k nodes behind the front pointer.At each step keep advancing both front and back by 1 node.When front pointer reaches end of link list, back pointer is at the last k’th node. |
answer: There’s other related question:Find kth-order(greatest) element from the unsorted array or list without sorting the whole list? |
question :
Design an algorithm to find out if an array has a pair of integers summing to some number X. |
answer: Perl: store all the array elements as keys in a hash. for each key see if (X-key) exists in hash. Return true and exit as soon as condition satisfied. Works only for unique non-duplicated integers in array. |
answer: Make a hash for all numbers [0-sum]. In each index store the number of times that number appears in the sequence. Scan the first half of this hash array. Check Count[Sum-index] and you got your answer. Linear |
question :
Complexity of this algorithm. How to improve the complexity? |
answer: N^2 and can be improved to n logn using binary serach. |
answer: or could be linear time if you’re allowed to use a hash table |
answer: I’m pretty sure hash table is the answer they were looking for… |
question :
You run a packing department where customer orders are categorized into small, medium and large batches. In general you try to rotate your packers between all sizes of customer orders since there have been prior cases reported of shoulder strain from folks doing large batches for a full shift Ian is your best large item packer; he can do twice the expected rate seemingly without even trying. He has been packing large items all morning. After lunch you see your queue has grown in the large batch area. If you keep Ian in the large item packing area, he can get the work accomplished without any impact to production. Or you would need to move two employees into backfill his role which may impact your overall production for the day. What do you do? |
answer: You redirect Ian out of heavy/large to swap with one of the two who replaced Ian. You inspire the rest of the team with a focus on those working the small category to pick up the pace to maintain the production. Ian is a long term asset and you protect him. |
answer: The company mission comes first, but not at the cost of safety and union contracts might have to be taken into account. Is the rotation union negotiated or simply a management decision? If simply a management decision, then it provides flexibility. Do not sacrifice the long term with short term success, which the general rotation rule aims to achieve. Ian is a valuable asset, but obviously can exceed the general rule. Clearly open the lines of communication with Ian. Keep him in the heavy/large to achieve the goal, but monitor him closely. At the first sign of him tiring, rotate him out without question. As the previous commenter stated, use your leadership to motive the rest of the team to succeed. |
question :
Given a set of numbers, partition the set in to two, such that sum of all the candidates in first subset = sum of all the candidate numbers in second subset. |
answer: Solved by factoring sum of entire set and finding all candidate numbers which sums up to that factor. That is if the set sum = 15. Factorize 15 such as 1+14, 2+13, etc. And find all the candidates in the set which sums up to 1 and 14(and so on). Then subgroup them. Then follow up was how to handle negative values, what if values are largely distributed like {-1M1, -1, 0, 1M} The above method performs miserably. One solution I gave was to reduce numbers by orders of magnitude. That is above set is equivalent to {-11, -1, 0, 10} and while finding out factors of sum, go from -x to +y where x being most negative and y being most positive value in a given set. |
answer: it’s a subset sum problem with the targetted sum equal to half of the sum of elements in the array. It can be solved usin DP. |
question :
Standard OOPS concepts like diff between interface and abstract class. |
answer: An interface is a group of related methods with empty bodies.An abstract class is a class that is declared abstract. |
answer: An abstract class is a class that can’t be instantiated directly and must be inherited to create a concrete class.An interface is an abstract class which provides no default implementation and just specifies the functionality a concrete class much implement. |
answer: I believe the best answer would be to say Interface does not have any default definition for a function whereas abstract class can.. So when we need to define some sort of default implementation, abstract class are better than interfaces.What SCH is correct too |
question :
Find intersection of two linked list. |
answer: People who ask such questions tend to like to see simple answers first and then keep asking you how to modify it to be faster. The simplest way is to traverse one list and for each element,. find out if it is in the other list. If so, add it to the returned set for an O(n^2) speed.You can then make it faster by copying one list into a set and then traversing the other list and testing each element for inclusion in the set and adding common elements into the returned set for O(n log n) speed.Finally, if the lists are sortable, start by sorting both lists. Then traverse them both at the same time by starting with a pointer to the first element in each list. Then in a loop while both pointers are not null, if they point to elements with the same value, add it to the returned set, and then advance the pointer to the element with the smallest value.for O(n) speed.I hope I got that right. |
answer: cutelyaware, you are mostly right.However in the scenario where they are presenting two linked lists that are joined at some point, the solution would be this :c1, c2. Find difference between the lists c1-c2 = d. Now traverse to the c1-d the element of the first list (the longer list). Then start comparing the elements starting from the (c1-d)th element of the first list with the first element of the second list. Move to the next element of both the lists till we find a equality match. That is the intersection point of two linked lists.Regards |
question :
Given a binary tree with only upwards (parent) node references, re-construct the tree adding in child references. You are given a list of leaf nodes (sorted in left to right order). Tricks include making sure to account for extremely unbalanced trees. |
answer: Recommend liberal use of queues |
answer: Can you elaborate pls.. |
answer: Can use a layer-by-layer recursive method. |
question :
Given a large file (>500GB), sort entries. |
answer: This would require an external sorting algorithm, such as external merge sort.Follow-up questions are likely to probe on performance optimizations: parallel sorting, chunk sizes etc. |
answer: Shell Sort or Comb Sort would work if you don’t have the additional 500GB of hard drive space needed for external sorting. |
question :
Given an array of size [i..n], find the product of all the elements of the array except for the element at index b, where b is an arbitrary element. |
answer: The trick here is that there’s a slow way and a fast way to do this. The slow way is n^2 and trivial. The quick way (there are actually 2 but one is a bit faster) is as follows in pseudocode:for x in [i..n] :– product = product*xproduct = product / bEssentially the solution is to run up a product and then divide everything by b. |
answer: Swap the element at index B with 1compute the product using a loop (as above)Index "B" will generate a "product x 1" condition. Which won’t change the product.This is cheaper than either doing a division at the end (division is expensive), or checking "is the index b? then skip it" during each loop iteration.Swap the element at index B with the original value |
question :
Write a code to determing whether a binary tree is symmetric or not (symmetricity is based on data i.e., folding the tree with respect to the root node, all the leaf nodes which overlap should have same data) |
answer: The Strings generated by doing a pre-order and post-order traversals should be reverse of each other |
answer: a pre-order traversal is enough, is the string is symmetric , then the tree is symmetric |
answer: If we do an inorder traversal and the result string is a palindrome, then the tree is symmetric |
question :
Difference between Heap and Stack |
answer: consider them as data structures, not memory related heap and stack ! |
answer: Heap: A tree with a property that the value at the parent should be >= value at its child (max heap).Stack: no such property. First in last out access |
question :
"Given a log file spanning multiple days, and given a page transition A -> B -> C, find all the unique users who made this page transition in the logs" |
answer: This one was doable. But we were short on time and the manager seemed annoyed to be there. |
answer: How is the transition encoded? Would a simple grep work? |
answer: Unlikely. The task was do it in Java 1.6, also they had to make the entire transition A -> B -> C, not neccessarily on the same line and maybe not even on the same date. Think Standard Web Server Logs.So you get:datetime – User X gets Page A…(millions of lines later)datetime User X gets Page B….(millions of lines later)datetime User X gets Page C….You get the idea. If I give you A -> B -> C, you get "User X" as out put, because they made the transition. |
question :
Write a function with input a list of integers and output the starting index of the longest sequence of ascending numbers e.g. 12123 -> 2 or 4567 -> 0 |
answer: public static int longestAscending (int[] vals) { int curStart = 0; int curLength = 0; int longestStart = 0; int longestLength = 0; for(int i=1; i<vals.length; i++) { if(vals[i] > vals[i-1]) { // Great. Keep going. curLength++; } else { // End of a run. if(curLength > longestLength) { // Run ended well. longestStart = curStart; longestLength = curLength; } curStart = i; curLength = 0; } } return longestStart; } |
answer: int main(){ int a[] = { 1, 2, 1, 2, 3, 4, 5, 6, 7, 4 }; int a1[] = { 4, 3, 2, 1, 0}; int N = sizeof(a)/sizeof(a[0]); /* length of a */ int ind=0, i=0, j, max=-1, lmax=0; while (i<N) { j = i; /* check ascending sequence */ while (j+1<N && a[j] < a[++j]) ; printf("Seq at %d %d\n", i, j-i); /* j-i == 1, when 2 numbers are not asc * j-i == 0, for last item (odd number elems) */ if (j-i <= 1) { ++i; continue; } lmax = j-i; if (lmax > max) { ind = i; max = lmax; } i=j; } printf("Max at %d, %d\n", ind, max); return 0;} |
question :
How would you count the number of words in a string consisting of uneven number of spaces between words( not dictionary words)? With and without library functions. |
answer: With -Use Java String Tokenizer or split function |
answer: int wc(char *s){ if (!s) return -1; int wc = 0; /* prune initial continuous spaces */ while (*s == ‘ ‘) ++s; /* count spaces, i.e words! */ while (*s != ‘\0′) { if (*s == ‘ ‘) { ++wc; s++; /* prune continuous spaces */ while (*s == ‘ ‘) ++s; } else ++s; } /* sentence can end without space, check last word has been accounted */ if (*(s-1) != ‘ ‘) ++wc; return wc;} |
answer: char str[] = "jdjd jdjd jriri";count=0;for(i=0; i<=strlen(str); i++){ // str[i] while(str[i]==’ ‘) { i++; } count++; while(str[i]!=’ ‘) { i++; }} |
question :
Given two arrays one with expected numbers and other with actual numbers determine which number is missing in the actual array |
answer: XOR all the elements together – the result will be the missing number.This works assuming there’s only one missing number, but it’s the fastest way. If there are multiple missing elements, use a hashtable. |
answer: missing = SUM(expected) – SUM(actual)(again works only if 1 no. is missing!) |
question :
There are 199 elements in array. It has only one distinct value? How will find this distinct value? Also for solution please tell about O(n)?How can you make it more efficient? |
answer: XOR all the elements. 198 are the same. The result will be 0 for them: A XOR A = 0. The result will be the distinct value. |
answer: Forgot to indicate: 0 XOR B = B. Therefore, the overall result will be the distinct B. |
answer: Above answer won’t work on a data set like: {3, 3, 3, 2, 2, 12} where there’s an odd number of non-unique values.The easy answer is that you could hash each element into a hash table which just contains a counter for each key add. Then you could go through the array again and look at the hash table to find the element that was only added once. |
answer: … for(int i=0 ; i< a.length; i++){ if(map.containsKey(a[i])){ map.put(a[i], (map.get(a[i]) + 1)); }else{ map.put(a[i], 1); } } for(Map.Entry<Integer,Integer> entity : map.entrySet()){ if (entity.getValue() == 1){ System.out.println("distinct element is: " + entity.getKey()); break; } } |
question :
how would you design how a cellphone implements its contact list when you press a certain letter. For example, If you press M it will tell you all the names starting with M. then if you press MI it will tell you all names starting from MI and so forth…. |
answer: Use a tree structure where each level is a consecutive character. So, if M is chosen first, travel down the "M" branch. To show remaining set of possible contacts, traverse the tree and print out all leaf nodes. |
answer: Use a trie or radix (patricia) tree |
answer: Keep a sorted contact list in an array. The names will be in char arrays so the access time is constant for a specific index. Do a binary search for the left boundary (the first appearance of a match and the right boundary (the last appearance of a match). Iterate through that index range. When dealing with mobile space might be an issue and making such a tree might cost more overhead then just looking through a sorted array. |
answer: The tree answer is a probably the right idea, but what about edge cases like if you have a contact Matt and a contact Matthew, in this case Matt will not be a leaf node but be an intermediary node on the way to Matthew. Any clarification would be appreciated |
question :
Write an algorithm to determine whether a given number is of the form (2^n)+1, where n is an integer. |
answer: Subtract one and then keep dividing by two until you either get to 1 (true) or the number is not evenly divisible (false). |
answer: return (n == 1) || ((n-1)&(n-2) == 0); |
answer: bool if_power(int n){ n–; return n&(n-1) ? false : true ;} |
answer: if(n%2==1) return TRUE else return FALSE |
answer: boolean isapower(int pow, int num);int main(){ int num = 2; int pow = 2; if(isapower(pow, num-1)) { printf("%d is power of %d + 1", num, pow); } else { printf("%d is not power of %d + 1", num, pow); } return 0;}boolean isapower(int pow, int num) { while((num > pow) && (num % pow == 0)) { num /= pow; }; return num == pow;} |
answer: if(n & (n-1))==(n-1) return true else return false |
answer: The simplest answer would be: (number & 1) == 1. The last bit should be 1. |
answer: Sorry. That answer is for checking odd or even. Not power of 2 + 1. |
answer: The interview candidate’s answer does not account for (2^0) + 1. It would return false for that.Another option. Assuming Int x contains the value:boolean correctForm(int x) {x–;String binString = Integer.toBinaryString(x);if (binString.charAt(0) == ‘0’) { return false;}for (int i = 1; i < binString.length(); i++) { if (binString.charAt(i) != ‘0’) { return false; }}return true;} |
question :
You’re in charge of new business venture x. What do you evaluate in vetting the business potential? Now what is your estimate of the volume we could move (with numbers)? |
answer: The first part is a fairly simple new venture analysis with all the concerns that come with it. I didn’t know what to make of the last part and I kind of think the interviewer was just trying to make me uncomfortable and see how I would react. |
answer: That is a pretty typical question. It may be intimidating, but market potential sizing is a problem you would need to be able to solve as a product manager. Usually, the interviewer is looking for you to validate/justify assumptions you made and walk through the logic of how you arrive at your estimations — to see how you would think, when an answer is not readily available, or the situation is ambiguous, with multiple possibilities, dimensions, or directions… such as for a new or emerging service or product, where reference or data points may be limited. |
question :
Write a function that allows to convert a string to the corresponding number (i.e. implement the atoi() C function) |
answer: int my_atoi(char* pStr) { if (pStr == NULL) { printf("ERROR: null string.\n"); return -1; } int num = 0; int pos; for (pos = 0; ; pos++) { char currChar = *(pStr+pos); // Check whether the current char is not a digit if ( currChar < ‘0’ || currChar > ‘9’ ) return num; // Read the number and add it to the ‘num’ variable num = (num*10) + (int) currChar – (int)’0′; } return num;} |
answer: int atoi(char *s){ int i = 0; while(*s) { i = (i<<3) + (i<<1) + (*s – ‘0’); s++; } return i;} |
answer: int atoi(char *s){ int i=0; while(*s) { i = i*10 + (*s- ‘0’); s++; } return i;} |
answer: Try testing for the above to sample codes, I have not really tested it on any compilers. |
question :
Given a (potentially large) array of integers, all but one repeating an even number of times, how would you find the one repeating an odd number of times in an efficient way? eg [1 2 3 3 2 2 1 4 2] should return 4 |
answer: Use any collection data structure to insert and remove the numbers, such that at the end the only one remaining will be the one repeated an odd number of times.For example we can use a tree. We consider on number at the time. We first search for the number in the tree. If found, we will remove it. Otherwise, we will insert it. At the end, the number (or the numbers, in general) repeated an odd number of times will be in the tree. For the complexity it is necessary to perform an amortized analysis.Another data structure that we can use is the hashmap. However, the space consumption and management could be high, if the map automatically resizes. |
answer: Ex-or the numbers. For the odd occurrence, the ex-oring will not result in zero. |
answer: Ex-oring is a great idea, one other solution is to sort the array and then in one pass you can find out the number that occurs odd number of timewith quicksort avg case nlogn and worst case n^2 |
answer: Few steps of counting sort can help us do it in O(n) time.Step I: find min and max, thus the rangeStep 2: initialize array of the range with 0Step3: as numbers come in, increment the a[number] by 1.Step4: scan the array to find the odd number. |
question :
Write a function to recursively reverse a string. |
answer: #include <string>string stringReverse(string str){ if (str.length() > 0) { return str[str.length() – 1] + stringReverse(str.substr(0, str.length() – 1)); } else { return ""; }} |
answer: public static String strRev(String st) { if (st.length()>0){ return (st.charAt(st.length()-1) + strRev(st.substring(0,st.length()-1))); } else return " "; } |
question :
Find a longest Palindrome in a given string. |
answer: Read the letters into a stack. Make a stack copy and pop the top (1 or 2, depends) letter(s) out when there’s a potential palindrome. |
answer: Reverse the string and perform longest common substring algorithm |
answer: Struggling through some of these problems so I can prepare myself. I kind of worked something out. It seems to do it in O(n), but the code turned out so simple that I am skeptical I actually got it. Syntax of some things may not even be right. Anyways, here’s my solution.public static String longestP (String mystring) { HashMap myhash = new HashMap(); int temp1, temp2; int i; int palindromeLength = 0; String longestPalindrome; for (i=0;i<mystring.length();i++) { if (myhash.get(mystring.charAt(i) == NULL) { myhash.add(mystring.charAt(i), int i); } else { int temp1 = mystring.charAt(i); String substring = mystring.substring(temp1, i); if ((checkPalindrome(substring) && (substring.length() > palindromeLength)) { palindromeLength = substring.length(); longestPalindrome = substring; } } } return longestPalindrome;} |
question :
Algorithm to produce the power set of a given set. |
answer: A set will have N elements and the number in a power set has 2^N elements, so therefore we build an array of 2^N element containers, which contain up to N elements each. We then construct a loop with a counter which starts at 0 and ends at 2^N. We do a bitwise comparison and each 1 means that we include that element in the current container index. A 0 means that we don’t. For example, if our set is {A,B}, then we would have 2^2=4 possible values. We would then loop from 0 to 3. 0={}, 1={A}, 2={B}, 3={A,B}. This is the power set. |
answer: @Jordan – beautiful algorithm! |
question :
Implement the floodfill algorithm of a paint program |
answer: I’m curious as to why everyone asked you about the floodfill algorithm. Did you have a lot of CG experience? Was the position in any way specific to anything in CG? |
answer: No, I was interviewing based on my web services experience. It’s a standard question to see whether you can solve nearest neighbor and other graph problems |
question :
Explain how the garbage collector works. |
answer: It is the systematic recovery of heap memory, by tracking usage of references to that memory. The recovery (freeing) can occur either immediately when the last reference goes out of scope or later by other defined parameters such as when allocated space reaches a certain threshold or the system is idle. The exact functionality depends upon the implementation. |
answer: A generic explanation could be:1-During the first pass GC marks in the heap the objects that are eligible to be freed, if all the references they hava are null.2-GC deletes all marked objects in the heap.3-The heap is compacted by the JVM to avoid memory fragmentation. |
question :
Given an array of unsorted integers, determine which number appears most often. |
answer: Seeing that it’s a stream of integers, using a hashtable would be your best bet.For each x in array: if hashtable has x: add 1 to hashtable[x] else: hashtable[x] = 1 |
answer: A hash table won’t work due to the potential of collisions. |
answer: The ideal solution, and the one I discussed with the interviewer was:Make a hash table. Run through the array and for each number, if the location in the hash table is empty, add 1, and if the location is taken, increment the count in that bucket. Once you’ve run through the entire array, simply determine which bucket has the largest number, and that’s your most common number (as well as how many times it appeared). |
answer: @2nd poster – a collision is the heart of the solution. A collision shows the element exists and hence increments the count |
answer: I think what the 2nd poster means is, you can have, say 123 and 847 hashed to the same location, then your result would be wrong. |
question :
say sth about hash table. |
answer: lots of detailed question followd |
answer: A Hash Table essentialy takes a hash of some given input block and constructs a table, which points to the source block. In many cases is arguably faster to use a hash table, because indexing into a table is much faster than comparing the complete block to every block the table references. It is useful in comparing strings for example. One can generate the hash, then use a binary search alogrithm to jump to the closest match. There are many different variations of hash table algorithms. Collisions can occur when two hash values are similar for different blocks. When that occurs, it is possible to use a second hash or to then perform a strict comparison of the blocks. There are many other variants and optimizations of this algorithm. |
question :
What is a Hash Table |
answer: Just google it |
answer: It is a synchronized version of Hashmap with an exception that it does not allow null keys and null values. Stores KEY VALUE pairs.What happens if you try to add a null key or value?Code will compile fine but you will get java.lang.NullPointerException on execution. |
question :
The math problem was the most difficult if you are not used to algebra type word problems. I am assuming that none of the people interviewing do this kind of thing on a daily basis. |
answer: I agree on the math problems. They are pretty simple if you have time to think them out. I had the initial answer correct, but when they changed the numbers after my explanation, I bombed. It was really simple, but I just chocked on the spot. I was able to work through the problem with their help and eventually found the correct answer, but it did not go as planned. I also was trying to complete the math in my head, versus using a calculator. When I finally reached for the calculator, it did not work. They went and found another one, but by that time I was flustered. I felt like I aced the other two interview sessions, but failed the math flow part. I am not expecting an offer Very professional interview and I was impressed in what they were willing to offer. I originally applied for the Operations Manager position, but during my travel to the city found out by a recruiter it was based off of talent and could be the Area Manager position. Very stiff competition within my interview peers from all over the United States. This was for the plant in Columbia, SC. |
answer: Sorry….."Choked" |
question :
Details about Hashtable? Good hash function? HashTable time complexities? Binary search complexity? |
answer: A good hash function has uniform distribution and low amount of collisions. Use of mod is common. Hash table is constant average case search time, whereas binary tree will take O(log n). |
answer: hash table time complexity is O(1) |
question :
Find the maximum subset sum in an array of numbers. Discuss complexity. |
answer: I assume you mean sub sequence, not subset.e.g. 4 8 -2 4 0 0 3 5 -30 12the max subset would be, 4 8 4 0 0 3 5 12 = 34but the max sub sequence would be4 8 -2 4 0 0 3 5 = 22you would need to track the start point of the current subsequence and its sum, when the sum becomes negative you would start a new subsequence and update the current max subsequence. |
answer: I assume you mean sub sequence, not subset.It can be solved in linear time but using a cumulative array instead of the original one.e.g. 4 8 -2 4 0 0 3 5 -30 124 12 10 14 14 14 17 22 -8 4find the max number and the min number before that4 – 22the max sum sub sequence are between these indicies and max value is the max sum |
answer: I think they asked about Maximum subarray problem:http://en.wikipedia.org/wiki/Maximum_subarray_problem |
question :
Find the max ;length palindrome in an input string. |
answer: A stupid and slow solution (O(n^3)): public static string MaxPalindrom(string str) { string maxP = String.Empty; for (int i = 0; i < str.Length; i++) { for (int j = i; j < str.Length; j++) { if (Strings.isP(str.Substring(i, j – i)) && j – i > maxP.Length) { maxP = str.Substring(i, j – i); } } } return maxP; } private static bool isP(string str) { for (int i = 0, j = str.Length – 1; i < j; i++, j–) { if (str[i] != str[j]) { return false; } } return true; } |
answer: Here’s a code with O(n2) complexity#include<stdio.h>#include<conio.h>#include<string.h>void ispal(char*,int,int*);void longpal(char *str){ int longest[2]={0}; int i=0; for(;i<strlen(str)-1;i++) ispal(str,i,longest); printf("\nLongest Palindrome: "); for(i=longest[0];i<=longest[1];i++) printf("%c",str[i]);}void ispal(char *str, int i, int *longest){ int j=i; while(i>=0&&j<=strlen(str)-1) { if(str[i]==str[j]) { if((j-i)>(longest[1]-longest[0])) { longest[0]=i; longest[1]=j; } } i–; j++; }}void main(){ char *str; scanf("%s",str); longpal(str); getch();} |
answer: My answer is based on http://stevekrenzel.com/articles/longest-palnidrometranslated to c language. |
question :
Given an array of integers, all but one of which appears an even number of times, find the one integer which appears an odd number of times. |
answer: I answered him that we can do a XOR, and then he asked me to it in another way and wanted me to write a code, read out so that he could note it. I wrote the code using HashMap. |
answer: XOR fails for an invalid input [2,4,6,6] as it will return 6.You should validate your args and in this case the cost of validating your args is the same as obtaining the solution |
answer: Create a hash set.Iterate through the array. If the set contains this value already, remove it Else add the value to the setIn the end, if a value was in the array an even number of times, it is no longer in the set. Otherwise, it’s still in the set. After iterating through the array, the set will contain only one value, the one that was repeated an odd number of times. |
question :
Write a program to reverse the words in a string in place. for eg; " I am sam " –> " sam am I " |
answer: Reverse the whole sentence letter by letter.Then reverse all letters in each word. |
answer: did you get any response from them whether u were through to the next round or not…i had a decent first interview but haven’t got any response…its been 3 days now…so was wondering do they let you know if u r through or just don’t call back if u r not through |
answer: yes, after a week. there will be 3 phone interviews of total. |
question :
What is the fast sorting algorithm and why? |
answer: quicksort or mergesort |
answer: Also, heapsort, which requires less space than mergesort but has same average case time |
answer: Its not quick or merge sort.. It is radix sort its O(n) where as both quick and merge take O(nlogn) |
answer: It’s kind of a trick question :|It depends on how the data is currently represented, how much space you can allocate, how many parameters are being sorted, etc. You need to know more about the data before you can give the best algorithm, there is no one-size-fits-all. |
question :
Write a program to reverse words in a string |
answer: #include <stdio.h>int main(int argc, char **argv){ int i; for(i = argc-1; i > 0 ; i–) { printf ("%s ", argv[i]); } printf ("\n"); return 0;} |
answer: The above answer isn’t correct, because it would reverse the order of the letters as well. For example: The quick brown fox => xof nworb kciuq ehT when it should be:fox brown quick The.You have to make another loop inside to traverse the length of each word, and then print that out in the correct order. |
answer: in java, you can use string split.public class TestClass { public static void main(String[] args){ String str = "The quick fox jump over the dog"; String[] strs = str.split(str, ‘ ‘); String result = ""; for (int i = strs.length-1; i > 0; i–){ result += strs[i]; } System.out.println(result); }} |
answer: public class TestClass{ public static void main(String[] args){ String str = "The quick fox jump over the dog"; String[] strs = str.split(" "); System.out.println("the output is: "); String result = ""; for (int i = strs.length-1; i >= 0; i–){ result = (result.length()>0?(result+" "):result)+strs[i]; } System.out.println(result); }} |
question :
Explain the data structure you would use to implement pop() and push(Object, int) for a Priority Queue. |
answer: I had said red black tree. He seemed to agree |
answer: Would a heap not be more appropriate? |
answer: Did you get the job? |
answer: No … I did mention it in my review. Interviewed and No offer. |
answer: I got this question as well. However, the answer is impossible in constant time. A self balancing tree is one way to implement this. In that scenario you have O(log n) time for insertion and removal. You can always have the get minimun in constant time. A van Emde Boas tree or Fusion Tree can speed up this time, but not bring it to constant time. |
question :
Mention one design pattern used in your project. Give me something good and bad about it. |
answer: I had to use an old C api, which I could not rewrite in order to maintain backwards compatibilty, but needed a useful COM interface from this C api. I could have a applied an adapter pattern over this C API, but instead chose to model the system appropriate singletons. I did apply an adapter pattern to those singletons, to better fit the COM model, but kept the singletons as close as possible to the original structure of the C Code underneath. It was good because it improved the C code. However the bad part is that it was difficult to make sure I did not alter the functionality of the existing code. It would have been safer just to wrap the COM layer around the C, but I took the hard path and improved the C code. It ended up being much more maintable in the end. |
answer: @Jordan – were you the candidate? Did you make it through? |
question :
Given array A of size n, generate array B of size n, such that: A[i] = B[i]/(Sum(A[0] … A[n-1]) |
answer: This is a confusing question. Why is the equation expressed with A on the left side when it is given to you? They ask you to generate B right?So it should be B[i] = A[i] * Sum(A[0]…A[n-1]If it’s just like this, then the algorithm is an easy O(n) algorithm.Create array B with size n, then go through A and sum all the elements up. Then go through A again, this time multiplying each entry by the sum and putting it into the respective B slot. |
answer: lol, i think the question is phrased wrong |
answer: I believe the given equation is correct. The equation is stating what the desired end result of the relationship between A[ ] and B[ ] needs to be not how to create it. To create B[i] the equation and following description given by Gofishus will be what you would use to get the end result of A[i] = B[i]/(Sum(A[0] … A[n-1]). |
question :
Reverse a sentence but keep the individual words in the same order |
answer: Complexity is O(n).Note. string is immutable object so I used stringbuilder for inplace reversal.class ReverseWords { public static void Reverse(ref StringBuilder strInput) { //Reverse the entire sentence Reverse(ref strInput, 0, strInput.Length – 1); //Reverse the words withing reverse sentence int startIndex = 0; int endIndex = 0; while (endIndex < strInput.Length) { if (endIndex == strInput.Length – 1) { Reverse(ref strInput, startIndex, endIndex); startIndex = endIndex + 1; } else if (strInput[endIndex] == ‘ ‘) { Reverse(ref strInput, startIndex, endIndex – 1); startIndex = endIndex + 1; } endIndex++; } } private static void Reverse(ref StringBuilder strInput, int startIndex, int endIndex) { for (int i = startIndex; i <= (endIndex + startIndex)/ 2; i++) { char temp = strInput[i]; strInput[i] = strInput[endIndex + startIndex – i]; strInput[endIndex + startIndex – i] = temp; } } } |
answer: What data structure solution has order 1 look up and is always sorted? |
question :
Write a function that takes in an array and repeats an integer that appears the most. |
answer: if: Array [2][2][3][3][3][2][1][2][1] it should print [3] |
answer: Confusing. In your example, 2 appears the most. Do you mean the integer that repeats the most consecutively? Cause that would be 3.Anyways, in either case, you can go through the array adding all the key-value pairs (number and times) to a hashmap and then access the hashmap in constant time. O(n). |
answer: class FindMostOccurences { public static DictionaryEntry MostOccurences(int[] Array) { Hashtable ht = new Hashtable(); for (int i = 0; i < Array.Length; i++) { if (ht.ContainsKey(Array[i])) { ht[Array[i]] = Int32.Parse(ht[Array[i]].ToString()) + 1; } else { ht.Add(Array[i], 1); } } DictionaryEntry de = new DictionaryEntry(0,0); foreach (DictionaryEntry item in ht) { if (Int32.Parse(item.Value.ToString()) > Int32.Parse(de.Value.ToString())) { { de.Key = item.Key; de.Value = item.Value; } } } return de; } } |
answer: Using map , i think one loop is sufficient.private static int mostReapeatingNumber(int[] is) { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int tempHighestCount = 0; int keyHighest = 0; for (int index=0; index < is.length; index++) { int number = is[index]; Integer numCount = map.get(number); if (numCount == null) { map.put(number, 1); } else { map.remove(number); numCount++; map.put(number, numCount); if (numCount > tempHighestCount) { tempHighestCount = numCount; keyHighest = number; } } } return keyHighest; } |
answer: I think there’s no need to have a map. Just maintain variables prev_max_run, prev_max_num, prev_num, curr_num and curr_run. In the loop if the prev_num was equal to curr_num increment curr_run. When you find the num is different check curr_run with prev_run. If curr_run > prev_run, prev_max_num = curr_num. |
question :
Compare and Book and a Three Ring Binder using data structures and classes. |
answer: Book would have a class pages, and page numbers. You would use an Array to store all pages of the book in an ordered sequence. Binder would also have the class pages, but you would use a linked list to add or remove pages at anytime. |
answer: A book is like an array. You can very easily look up based on index (page number), however it is hard to insert (you’d have to cut out pages, put one in, and put pages back in). A binder has a more difficult lookup, but insertions are easy (like an unsorted list) |
question :
Find the angle between the hour hand and the minute hand on a clock given the hour, minute and second. |
answer: Imagine yourself holding the clock in your hands and constantly turning thewhole clock in the counterclockwise direction at the same speed the second handis turning, so that the second hand doesn’t move at all, but stays in the sameplace.Now imagining that situation (with the second hand not moving at all), the hourhand makes one revolution every 10 seconds. Therefore the hour hand’s rate is360 degrees per 10 seconds or 36 degrees per second.Still imagining that situation (with the second hand not moving at all), theminute hand makes one revolution every 20 seconds. Therefore the minute hand’srate is 360 degrees per 20 seconds or 18 degrees per second.So the angle between the hour and minute hands grows at the rate of 36-18 or 18degrees per second, and since 18 degrees per second is the same as 360 degreesper 20 seconds, then the angle between the hour and minute hands grows at therate of 360 degrees per 20 seconds. Therefore they pass each other every 20seconds. |
answer: A 12 hour clock has 12 part with each 360/12 = 30 degreesan hour is 3600s so the short hand (hour hand) mathematicaly (not physicaly!) move through each hour (that 30 degrees) by 3600 step. each step would be 30/3600 = 1/120 ~= 8.3 mili degreeFor the long hand (minutes hand) each of those 30 degrees parts would be 5min having 300 steps. So each step of this hand is 30/300 = 0.1 degreeand finaly for the seconds hand that 30 degree part means 5 seconds so each step would be 30/5 = 6 degreeYou can find the angle of all three hands in any moment by these information :for 1:15:13angle between "seconds hand" and 12 = 13 * 6 =78 degreesangle between "minutes hand" and 12 = 15 * 6 + 13 * 0.1 = 91.3 degreesangle between "houres hand" and 12 = 1 * 30 + (15*60+13) * 1/120 = 37 + 73/120 ~= 37.61 degreesand the angle between any two hand would be the subtraction of these. |
answer: angle = (h/12 + m/(12×60) + s/(12x60x60)) – (m/60 +s/(60×60))if angle is -ve then angle = |angle|So 2 angles made are angle and (360 – angle). |
question :
How do you find the fifth last element of the linked list using only one traversal |
answer: Use an additional pointer that is five nodes ahead of the first one. When that pointer reaches null, return the first pointer. |
answer: it can be a recursive function. once it hits the last element a counter goes off during backtrack. when counter hits 5, you can return the node. you can also save number and the node in a pointer instead.int number = 0;node findFifth(node first_item){if(first_item.getNext()!=null){first_item = first_item.getNext();}count++;if(count == 5){return first_item);}} |
answer: Using recursion requires more memory on the stack than using two pointers. |
question :
Intersection of arrays |
answer: I assume they are sorted else it doesn’t make much sense. If the first number is less than the second number, the second array was added onto the end of the first one, and just return the middle. Else Recursively binary search the array for when the left number is < than the right number and this the point they intersect. |
answer: is it arrays or linklists? It doesn’t make much with arrays since arrays will be in their own separate memory. Or am I missing something here? |
question :
Word count of a paragraph |
answer: Just go through the String or Array and keep track of the number of delimiters (space,comma,period,etc). O(n). |
answer: use the split function and get the length of the array. |
question :
In an array, all numbers appear even times, while on number appears odd times. Find that number |
answer: iterate the array and take the XOR of all numbersafter the loop is over you ll get the number.int res = array[0]for (int i = 1; i< array.length; i++){ res^=array[i]}print "number occuring only once is " + res |
answer: Iterate through the entire array and maintain a hash table of frequencies. Then read the Hash Table to get the one with the odd occurance (%2!=0)Kaustubh’s answer is O(n) time complexity … Mine is O(n) space complexity – requires additional data structure but is easier to get to in an interview. |
question :
Design a "Subscriber – Broker – Publisher" architecture (a) running on a machine; (b) running on a cluster. Write the code for the 3 classes. Details: there are Events, specified by an "event type" and a blob of detailed info. Each subscriber subscribes with a Broker for a certain event type that it wants to get. Subscribers send events to the broker, and the relevant subscribers need to be notified. |
answer:
This post has been removed. Please see our |
answer: The observer and observable design pattern can come in handy here. Or if you wanted to do it without the interfaces, simply maintain a list of all publishers in the broker and a map of which subscibers can be attributed to a particular publisher. then whenever there is an event from the publisher, simply notify all the subcribers for that publisher. |
question :
Print all permutations of a given string. |
answer: # include <stdio.h># include <conio.h>/* Function to swap values at two pointers */void swap (char *x, char *y){ char temp; temp = *x; *x = *y; *y = temp;}/* Function to print permutations of string This function takes three parameters: 1. String 2. Starting index of the string 3. Ending index of the string. */void permute(char *a, int i, int n){ int j; if (i == n) printf("%s\n", a); else { for (j = i; j <= n; j++) { swap((a+i), (a+j)); permute(a, i+1, n); swap((a+i), (a+j)); //backtrack } }}/* Driver program to test above functions */int main(){ char a[] = "ABC"; permute(a, 0, 2); getchar(); return 0;} |
answer: a string of N characaters will have following number of string combinationNp1 + Np2 + Np2+…NpN |
answer: Using recursion we can solve this. I am giving the pesudo code with a small example.let the string be "abc". I am showing the recursive call within the bracket itself. Just to understand. Don’t confuse that this is a code inside permute function.permute(abc){—-level 1—–letter saved at this level is = a;all combination List obtained at this level = permute(bc); after the call returns put the saved letter {a} at each position in each entry and do the same for all entry in the list List obtained here is only bc and cb; that means put a every position of the return bc and cb —-> for bc {abc,back,bcd} and for cb {cab,cab,cba} return all the entries.At the highest level you will get all the permutation of the string.————–level 2———– letter saved = b ; all combination List obtained at this level = permute(c); after the call returns put the saved letter at each position in each entry and do the same for all entry in the list List obtained here is only c; that means put b every position of the return c –> bc{putting b before c} and cb{putting b after c} return bc and cb. ————–level 3———– letter saved = c ; all combination List obtained at this level = 1; //Here it only c is returned Last letter is returned as this is only 1 combination exist — base condition of recursion.} |
answer: C# code. I’m a tester, so my code is a bit rusty, but the algorithm works.public static void Permutations(string orgStr) { List<string> permutations = new List<string>(); _perm(orgStr.ToCharArray(), String.Empty, ref permutations); foreach (string str in permutations) { Console.WriteLine(str); } } private static void _perm(char[] sample, string filled, ref List<string> permutations) { if (sample.Length == 1) { string perm = String.Format("{0}{1}", filled, new string(sample)); permutations.Add(perm); } else { for (int i = 0; i < sample.Length; i++) { char currChar = sample[i]; string newFilled = String.Format("{0}{1}", filled, currChar); char[] newSample = new char[sample.Length – 1]; for (int j = 0; j < sample.Length; j++) { if (j == i) { continue; } if (j > i) { newSample[j-1] = sample[j]; } else { newSample[j] = sample[j]; } } _perm(newSample, newFilled, ref permutations); } } } |
question :
Given the head pointers to two linked lists of unknown length, find the node of intersection if they do intersect. |
answer: Suppose that the pointers are head1 and head2. Move head1 and increment a count1 till head1 reaches null. Move head2 and increment count2 till head2 reaches null. If head1 > head2 or head2 > head1, move the respective pointer to such a position in the linked list so that the length of the linked lists from there are equal. Then, start checking if both pointers point to the same node and incrementing both until that condition is met.If they do point to the same node at some point, that is the node of intersection. Otherwise, there is no intersection. |
answer: I don’t understand the interview candidate’s solution. I don’t think I will work properly. If the last 3rd node of List A and last node of List B intersects, this algorithm will not find the answer.My solutions: Suppose length of List A is m, length of List B is n,If space cost is more of a concern, do a O(n^2) search because it will cost constant space to find the intersect. (nested for loop)If time is more of a concern,1. traverse through both list to figure out the length. Identify the smaller list(suppose it’s list A). cost O(m+n).2. traverse List A, build a binary search tree with the address of pointers of the list as payload O(m log(m)).3. Traverse through list B and search the tree for each element in list B. if found, then it’s the intersection.O(n log(m)).the general complexity is O(m+n+(m+n)log(m)) = O((m+n)log(m)). If we don’t suppose A is the shorter, then the time complexity will be O((m+n)log(min(m,n))) |
answer: pblm can be solved by making a circular linked list.Start with head1 and traverse thru the list and modify the lastnode.nxtptr -> head2Now start with head2 and traverse. If you reach the head2 again then the list do intersect. |
answer: Vijay has the best solution with linear time. |
answer: Vijay’s solution works great for finding out whether they intersect, but the question asks for finding the node of intersection.I think William’s solution will work best for finding the node of intersection. The obvious one is an O(n^2) solution by traversing the first list with the nodes of the second list and doing a comparison. |
question :
Write a program to find the square root of a double. |
answer: use binary search to narrow down the search space and keep multiplying the answer in each iteration by itself to check if it is equal to the double given. If it is lesser, move up the lower bound, else move down the upper bound. |
answer: One easy to remember method that also has much better performance than binary searching for the result is the Babylonian Method. It is similar to Newton’s method for finding derivatives. See the algorithm here: http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_methodAlso, combining this algorithm with the Rough Estimation also described on that page will compute the squareroot of most double numbers in less than 10 iterations. |
answer: Is it too obvious to ask if you can do double^.5 ? |
answer: I would respond by showing that I am thinking about the problem as it is defined, not by making assumtions about what is implied. This can result in product that does not meet the requirement specifications, which can be very costly:"What do you mean, a program or a function? A program would require input and output mechanisms to make it meaningful, but makes it pretty usesless as a job assessment question. A function makes more sense in this context. " |
answer: There’s a variation of the problem which says "find the square root of a double up to the third decimal digit". I’d just multiply the original number by 10^position (meaning, for 3 digit accuracy it’d be 10^3) and ran a simple loop to find the closest integer. As soon as i*i > 10^position * number, you can return (i-1)/10^position. It’s hella slow and unimaginative, but it works and you won’t sound like you knew this problem ahead of time (if you come up with a Babylonian solution). |
question :
Find the last element of a linked list. |
answer: public *Node LastElement(Node *Head){while(Head->next != null){Head = Head->next;}return Head;} |
answer: Did they really ask you this question? Although Praveen’s answer is correct, It seems that his answer would also be very time-consuming. Is there another way to find the last element on a linked list – assuming that it’s singularly linked? |
answer: Did they really ask you this question? Although Praveen’s answer is correct, It seems that his answer would also be very time-consuming. Is there another way to find the last element on a linked list – assuming that it’s singularly linked? |
answer: praveen’s answer is correct but not good enough, you would not want to modify the pointer you got it might be your only ptr to the head of the list.public *Node LastElement(Node *Head){Node *iter = Head;while(iter->next != null){iter = iter->next;}return iter;}would be more correct. |
answer: Because the parameters are always passed by value. Even if you modify the input parameters, the original variable remains unchanged. |
answer: I am talking about the case where you don’t specifically pass the params as references in C++. In C, my statement holds. |
answer: All the answers are partially correct.Anonymous: The function accepts a pointer not a reference to the pointer (pass by value). Hence if the pointer ‘Head’ is modified in the function, it doesn’t affect the actualy pointer that was passed into the function.However, what’s missing in Praveen’s solution is the boundary condition of whether the Head node is NULL. If it is, then the starting statement of the while loop is going to access a NULL pointer.The correct solution should be something like:Node* GetLastNode(Node* head){ // Loops through till the end of the node for(; head != NULL && head->next; head = head->next); // Return the last node (This could be NULL if head was NULL). return head;} |
question :
What thing should I know about you that I failed to ask? |
answer: I told them that I had really felt we have covered all the ground very thoroughly. |
answer: Never answer any interview question with "I don’t have a reply". There is always an answer. The interviewer isn’t looking for the answer, just how you reply. Giving an answer shows you’re thorough and have thought through the range of possibilities. For this question, be prepared with about 5 more obscure traits that most interviewers fail to ask, pick one to answer and try to make it tie into the job. Make sure they are positive in every way. Most people interpret this question as seeking something negative, it’s not defined that way. |
question :
function: Divide 2 number without using divide operator |
answer: Right shift the number by 1 bit. |
answer: Subtract the smaller number from the larger number until the result is less than the smaller #. Count the iterations. |
question :
Given an array of 100 integers where every integer from 1-101 occurs once, except for one. Find the missing integer. |
answer: sum of number from 1 to n is n(n+1)/2So Sum from 1 to 101 = (101*102)/2 = 5151So missing number is 5151 – (sum of all elements in the given array) |
answer: Let a = XOR of all elements in array and b = XOR of all numbers from 1 to 100. The final result is a XOR b |
question :
None were really difficult, but I had diffculty answering anything that required impromptu math. I’m a spreadsheet guy. I.e. if you could buy the same quantity of two products one with a 10% margin and a higher cost and one with a 20% margin and a lower cost which would you buy? |
answer: I answered the lower cost item because of the higher margin, but because of the qty restriction it actually makes sense to buy the lower margin more expensive item because you will net higher profits. |
answer: You would have to look at other qualitative data (ie. consumer response) – Lets say the qty is 100 units of each. If Prod A is $200, 10% margin = $20 and Prod B is $100, 20% margin = $20. same thing. Look at demand forecast. |
question :
You have an integer array of length N, containing values in the range 1,2,3…N^2. Sort the array in O(N) time |
answer: We are given N value. So that we can find N^2 value. We can count number of digits in this value.. lets say number of digits is k.Then apply Radix sort for k times. Order of complexity is O(kN) can be written as O(N).search for Radix sort if you dont know.. (ofcourse u do this.) |
answer: One can make use of counting sort for this problem. |
question :
3 metrics on how to measure success on a software solution that has just been implemented in the page |
answer: it was a fallow up from a previous question… just take your time and be calm |
answer: 1) # of sales before and after, obviously2) click-through rate before and after (it tells me how intuitive the UI is for the user, as well as if there is a bug at a certain point, causing a dropoff in the CTR)3) # of visits to the help page/FAQ page before and after (it tells me that the user might be unfamiliar with the UI) |
question :
Code to find median in BST |
answer: Step 1) Do a Breadth first search/dump to count the number of elements.Step 2) Count half of that in your second breadth first dump and return the element. |
answer: Where n = number of elements in the BST, use an in-order Depth first search to traverse the tree and return element n/2 + 1. (The +1 is needed, assuming that n is an odd number and there is a true single median value.) |
question :
Code to check if a Binary tree is symmetrical. |
answer: typedef struct _Tree { struct _Tree *left, *right; …} Tree;int count_nodes(Tree *t){if (t == NULL) return 0;return 1 + count_nodes(t->left) + count_nodes(t->right);}int is_symmetrical(Tree *t) {if (t == NULL) return 1;return is_symmetrical(t->left) && is_symmetrical(t->right) && count_nodes(t->left) == count_nodes(t->right);} |
answer: Or you could prepare a string representation of the in order transversal, a symmertrial BST will have a palindrom-ic string representation. |
answer: Try something like huffman coding. 0 for left, 1 for right. Traverse and check for palindrome |
question :
what is the bubble sort algorithm |
answer: the alogrythm used for |
answer: standard algo Best O(n) worst O(n2) casefor(int i= count; i>=0;–i)for(int j=0; j <count; ++j)if(a[i] > a[i+1])swap(a[i], a[i+1])can do swap wit xor swapa[i] = a[i]^a[i+1]a[i+1]=a[i]^a[i+1]a[i]=a[i]^a[i+1] |
answer: int[] bubbleSort( int[] input ) { int swap_occurred = 1; while (swap_flag) { swap_occurred = 0; for (int i=0; i<input.length-1; i++) { if a[i] < a[i+1] { swap(a[i], a[i+1]) swap_occurred = 1; } } //for } //while} //method |
question :
Given a integer array, find the subsequence with max sum. |
answer: Kanade algorithm, coded as a charm. |
answer: int maxSubSum(const vector<int> &a){int max = INT_MIN;int temp = 0;vector<int> sub;for(int i =0; i< a.count; ++i {temp +=a[i];if(temp>max) {max = temp;sub.push_back(a[i])}return max;}} |
question :
Given an infinite stream of numbers, find the top 50 integers. What’s the data structure to use, and what’s the time complexity. |
answer: Use a min-heap. |
answer: Use a B-Tree with max degree 50. The worst case complexity should be O(log n) for insertion as well as search |
answer: if you are using a min heap and say the first insertion you do happened to be the largest element. then? |
answer: @birbal: First, you should let the min-heap fill completely and then you should compare every incoming number with the top element and insert that in the heap if it is greater than the least element. I have the working code with me… |
question :
Find the longest subsequence in a given array of numbers in O(n) |
answer: //Given an array of numbers find the longest subsequence//Using hash_maps :: complexity O(n)#include <iostream>#include <vector>#include <ext/hash_map>#include <map>#include <string.h>#include <sstream>using namespace __gnu_cxx;using namespace std;void itoa(int i,string *s){std::stringstream out;out << i;*s = out.str();}struct eqstr{ bool operator()(int i, int j) const { string str,str1; itoa(i,&str); itoa(j,&str1); return (str.compare(str1) == 0); }};typedef hash_map<int, int, hash<int>, eqstr> myHash;int main(){ myHash array; int inputArr[20] = {1,43,4,5,6,17,12,163,15,16,7,18,19,20,122,124,125,126,128,100}; int seqSize = 0; vector<int> longSeq; vector<int> tempLongSeq; for(int i=0;i<20;i++){ array[inputArr[i]] = inputArr[i]; //save value } myHash::iterator it = array.begin(); tempLongSeq.push_back(it->first);seqSize=1; ++it; int data; //Iterate through each element and check if it is the next in sequence for (; it != array.end(); ++it) { data = it->first; if(data==(tempLongSeq[tempLongSeq.size()-1]+1)){ tempLongSeq.push_back(data); seqSize++; }else{ //sequence ended if(seqSize>longSeq.size()){ //if the current sequence is longest then store it else longSeq.clear(); longSeq = tempLongSeq; } tempLongSeq.clear(); tempLongSeq.push_back(data); seqSize=1; } } cout<<endl << "Longest Sequence "; for (int i=0;i<longSeq.size();i++) cout<<": "<< longSeq[i] ;}///! Output :: Longest Sequence : 15: 16: 17: 18: 19: 20 |
answer: Hey guys… the above code needs changes. if values are greater than 193 than it should fail because of hash_map’s bucket_count.. anyways.. use map instead of hash_map. which is sorted. but this gives a complexity of O(nlogn) |
answer: How about:Traverse the array,have an initial index of start of sequence, and update the end index each time the next element is in sequence. If the sequence ends, check the difference between start/end, and if it is greatest so far than save those two indices and length of sequence. |
answer: Question – Should only the successive sequence of numbers be taken into account or sequence of numbers formed from the numbers in any position? |
question :
Describe the thread states in Java |
answer: New, Runnable, Not Runnable, Dead |
answer: from javadocNEWA thread that has not yet started is in this state.RUNNABLEA thread executing in the Java virtual machine is in this state.BLOCKEDA thread that is blocked waiting for a monitor lock is in this state.WAITINGA thread that is waiting indefinitely for another thread to perform a particular action is in this state.TIMED_WAITINGA thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.TERMINATEDA thread that has exited is in this state. |
question :
What is the name of the Java garbage collection algorithm |
answer: who wud ask this retarded question |
answer: answer with all types of algo with which latest JVM s released with instead of mocking it |
question :
Design a system for counting how many times an item is clicked on. You need to record clicks and be able to report how many clicks for a given item. Be able to report which items are the most popular. Keep in mind scalability, since this is Amazon we’re talking about. |
answer: Have a hashmap that takes name of the item as keyvalue and the stored data contains number of clicks. which is incremented every time.Initially a deque of size ‘k’ stores number of clicks for ‘k’ popular items i.e. the deque is sorted. Everytime we increment the number of clicks for an item we check the min/max values for the deque i.e. begin and end values if the value lies in between then we found a new popular item.We insert into the deque by traversing the deque. finding a location in the deque is log2(k) {k popular items}. we pop the one in the end. |
answer: Uhm… how is that going to work when you’ve got a whole farm of servers trying to count clicks for those items? |
answer: I’d rather using BST or STL map because you need to sort each item in less time. |
answer: I assume the point is scalability. You may do this useing sharding technique in order to split table records on multiple nodes |
answer: Why not try min heap |
question :
Given two lists, A and B, of sizes n and k, respectively, describe an algorithm to determine the intersection, C, of the two lists. What is the complexity of your algorithm? (The obvious solution is O(n*k)). Can you describe a solution that is faster? (An optimized solution can do it in O(n+k)). |
answer: The obvious solution compares each element of list A with each element of list B, searching for intersection. The optimized solution utilizes a hash table. |
answer: A[5] = {3,5,6,9,10}B[6] = {2,3,4,6,9,10}C[6] // Declare maximum size among two arraysSteps:======1. Sort Array A[] and B[]2. Compare A[aindex] == B[bindex] , == IF TRUE, ADD TO C[] == aindex++, bindex++ recursive Call to method again with new aindex,bindex3. IF A[aindex] > B[bindex] , bindex++ recursive Call to method again with aindex, new bindex4. IF A[aindex] < B[bindex] , aindex++ recursive Call to method again with new aindex, bindex |
answer: Suresh’s approach will not get O(N+K) complexity.Sorting individual list itself will cost O(nlogn) plus O(n+k) in merge sort.I think hash code will get O(n+k) complexity. |
answer: Dynamic programming, see longest common subsequence |
question :
What algorithm would you use to search a sorted list? What is the complexity of the algorithm? Implement the algorithm in your language of choice. |
answer: Interviewer was looking for binary search and its implementation. |
answer: in a list? |
question :
An integer is represented in binary as a sequence of 0’s and 1’s. Write a function that returns the number of 1’s in the binary representation of a given integer. |
answer: This is the "bit counting" problem, solved optimally as follows:unsigned int v; // count the number of bits set in vunsigned int c; // c accumulates the total bits set in vfor (c = 0; v; c++){ v &= v – 1; // clear the least significant bit set} |
answer: Lets consider 14(1110) is the numberint CountOnes(int Number){int n=0;while(number !=0){if(number%2==1) n++;number >> 1;}return n;} |
question :
Write a function to find the node where two linked lists meet. |
answer: public static void main(String[] args) { List<Integer> L1 = Arrays.asList(1,2,5,7,9,10,12,18,3); List<Integer> L2 = Arrays.asList(2,3,4,8,9,9,10,11,12,18); LinkedList<Integer> list1 = new LinkedList<Integer>(); list1.addAll(L1); LinkedList<Integer> list2 = new LinkedList<Integer>(); list2.addAll(L2); System.out.println("L1 : " + list1); System.out.println("L2 : " + list2); ArrayList<Integer> result = new ArrayList<Integer>(); System.out.println("two linked lists meet: " + findCommon(list1, list2,result)); } public static ArrayList<Integer> findCommon(LinkedList<Integer> list1,LinkedList<Integer> list2,ArrayList<Integer> result) { if (list1.isEmpty()) return result; int pop = list1.pop(); if (list2.contains(pop)) result.add(pop); return findCommon(list1, list2, result); } |
answer: // solution in C++#include <iostream>#include <map>using namespace std;// simple Node classclass Node{public: Node(int v) : val(v), next(NULL) {} int val; Node* next;};// function to find intersection NodeNode* findNodeWhere2ListsMeet(Node* head1, Node* head2){ // interate through first list and populate map map<Node*, int> nodeMap; while (head1 != NULL) { nodeMap[head1] = head1->val; head1 = head1->next; } // interate through second list and try to find in map while (head2 != NULL) { if (nodeMap.find(head2) != nodeMap.end()) { return head2; } head2 = head2->next; } return NULL;}// test code (happy path only)int main(){ // linked list 1 values = 1,2,3,4,5,6 Node* head1 = new Node(1); Node* n12 = new Node(2); Node* n13 = new Node(3); Node* n14 = new Node(4); Node* n15 = new Node(5); Node* n16 = new Node(6); head1->next = n12; n12->next = n13; n13->next = n14; n14->next = n15; n15->next = n16; // linked list 2 values = 11,12,13,5,6 Node* head2 = new Node(11); Node* n22 = new Node(12); Node* n23 = new Node(13); head2->next = n22; n22->next = n23; n23->next = n15; Node* intersection = findNodeWhere2ListsMeet(head1, head2); while (head1 != NULL) { cout << head1->val << " "; head1 = head1->next; } cout << endl; while (head2 != NULL) { cout << head2->val << " "; head2 = head2->next; } cout << endl; |
answer: Previous answer got truncated. Here’s the last of the test code starting at the function call. Node* intersection = findNodeWhere2ListsMeet(head1, head2); while (head1 != NULL) { cout << head1->val << " "; head1 = head1->next; } cout << endl; while (head2 != NULL) { cout << head2->val << " "; head2 = head2->next; } cout << endl; cout << "lists intersect at " << intersection->val << endl; cout << "\n\n\nPress Enter to quit. "; cin.ignore(); return 0;} |
question :
You are given a binary search tree of integers. Given a target integer, find the greatest integer that is smaller than the target integer. |
answer: It is the predecessor of the given target integer. Get the target integers left child and then travel right until you hit null. |
answer: The target’s left child might be one of the numbers. But the exact number just less than the target number will be given by doing an inorder traversal of the BST and finding the number before the target number. |
question :
Regular Expression for finding US Zip Codes ? |
answer: Regular Expression for US Zip CodeRules: 5 digits-4 digits OR 5 digits <space> 4 digits OR 5 digits only\d{5}(-\\d{4})?Escape appropriately when using in a String. eg: \\d |
answer: \\d{5}(-\\d{4})?This is only for Rules: 5 digits-4 digits OR 5 digits only |
question :
Find Common elements from two same sized Integer Arrays(Unsorted) in O(n) without sorting either of them. |
answer: #include<stdio.h>main(){ //take arrays of three elements for comparision int a[3]={1,2,3}; int b[3]={1,4,2}; int i,j; j=0; for(i=0;i<3;i++) { if(a[i]==b[j]) { printf("common elements are:%d\n",a[i]); } if(i==2&j!=2) { i=0; j++; } }} |
answer: That is N*N complexity, cleverly disguised as single loop. Resetting i every time it reaches N and incrementing j does it. |
answer: Hash 1 Array 1Look up for each element in Array 2Append to common element array if found.O(N) |
question :
Optimize a system for finding pairs of numeric values in a list which sum to a specified third value. |
answer: Sort and traverse the list in both directions (i >= 0, j < Count), trying to find list[i]+list[j]=Sum. End when j < i. O(n Log n) complexity. |
answer: The previous answer seems to assume that all elements are positive. So, intead, create a search structure (by sorting or creating a hash table) and then for each element search for another element that is the difference between the sum and the the given element. |
question :
The manager of component ‘A’ says his functionality is more important than that of component ‘B.’ The manager of component ‘B’ says his is more important than that of component ‘A.’ You can only implement one A or B, but not both – which do you choose to implement. |
answer: I reference the Product Plan and select the component w/ the higher priority. The interview says "There is no Product Plan." I say "I select the one w/ the higher ROI." They say "there is no ROI." I say "then I choose the component whose manager has the best rationale." |
answer: I would say to do my own research |
answer: I would say whichever is more valuable to customer & gives competitive advantage to Amazon. |
answer: The key question to ask is definition of "IMPORTANT". Is it important to the managers (ego equation), important to the end consumer or important for Amazon. The first one needs to be thrown out immediately and the others must be quantified based on achievability, impact on end user and ROI. |
answer: Agreed. Need to drill into what "important" means. Great catch My guess is that Amazon was looking to quantify/define "important" from the customer perspective. |
question :
Linked list questions |
answer: here it is (untested, let me know if i am wrong)Node* Reverse(Node* Head){ Node* p = Head; Node* temp = null; Node* pr = null; while(temp) { temp = p->next; p->next = pr; pr = p; p = temp; }return pr;} |
answer: Loop will never be executed since temp is initialized to NULL. |
question :
How would you implement a priority queue? |
answer: Like a sorted linked list sorted on the priority. |
answer: use heap |
question :
Dig details how I create\implement something in my current job |
answer: I can’t tell the interviewer much due to non-disclosure agreement with my company. The interviewer seems not happy with my answer. |
answer: As a hiring manager, my advice is to answer this question from a behavioral standpoint. You don’t have to go into product, organizational, or other confidential details; you just have to show that your job gives you the experience the hiring manager is looking for. If you refuse to talk about what you do on at least an abstract level, you’ll have a pretty hard time on the average interview. I know I wouldn’t continue with a candidate who didn’t want to talk about their work experience. |
question :
Given an array of integers and an arbitrary integer, find the number of pairs of integers in the array whose sum is equal to the arbitrary integer. |
answer: findCombination(int[] array, int sum) { sort(array); // O(n*log n) int i = 0, j=array.length-1; while (i < j) { if (array[i]+array[j] < sum) i++; else if (array[i]+array[j] > sum) j–; else { print(i,j); i++; } }} |
answer: You have to use the "skeeve" algorithrm for these questions. its what they’re all looking for. |
question :
Given array of integers, find the first pair add up to 10. Analize your solution. |
answer: using hashmap, loop through the array once, and populate the map with10-array[i] as key and i as value. loop again and check the map if map.get(array[i]) != null. if the map has a value the value is the index of the other number. break out of the loop. (part that I didn’t answer is about 5,5 case that you have to check value from the map must not be the same as the current index.) This is O(2n) = O(n), linear solution. |
answer: using hasmap O(n) solution:for every element i in array if arr[i] <= 10 if (hashmap.containskey(10-arr[i])) // no. corresponding to reqd pair is present. return arr[i] else hashmap.put(arr[i],1) |
answer: #define SIZE 8int tab[SIZE];int sum;for(i=0; i<SIZE ; i++){ sum=tab[i]; for(j=i+1; j<SIZE ; j++) { if((sum+tab[j])==10) { printf("\ni is: %d, j is: %d", i, j ); i=SIZE; break; } }} |
question :
Given array of integers representing historic stock prices. Find the buying and selling points to maximize the profit. (original: You can hold the stock for only 30 days maximum.) |
answer: global profit, global min index, global max index. local min index, local max index. local profit. lmini = 0, lmaxi = 1, lp = [1] – [0];for (int i = 2; i < length-1; i++) { if ([i] < [lmini] ) { lmini = i; lmaxi = i+1; lp = [lmaxi] – [lmini]; if (lp > gp) { gp = lp; gmini = lmini; gmaxi=lmaxi; } } else { lmaxi = i; lp = [lmaxi] – [lmini]; if (lp > gp) { gp = lp; gmini = lmini; gmaxi=lmaxi; } }}gp is the profitgmini = the buying pointgmaxi = the selling point |
answer: Data Type: Profit(day bought, day sold, profit)MaxHeap<Profit> mh;Profit gain(int[] prices) {Profit p = new Profit(0,0,0);for (i=0 to n-1) { for (j=i+1 to min(i+30,n-1)) { Profit t = new Profit(i,j,prices[j]-prices[i]); if (t.compareTo(p) > 0) p = t; }}return p;}Profit now contains maximum possible profit and day to buy and sell.Complexity O(30*n) = O(n) |
question :
Given two large files of integers, only one byte difference. Find out this byte if memory is limited. What if memory is unlimited? Tell the complexity of your algorithm and analyze it. |
answer: I would go by divide and conquer approach. If the 2 files differ only a single byte, that means (say) file 2 has 1 character more than file1. So I would read the middle of both files. If the characters match I would read at 3/4th of the file. and continue comparing a character until I have difference of characters. From there to last read position, do a divide and conquer approach. In the end when I reach less than 512/1024 bytes (i.e bytes per track) I compare complete track. |
answer: Open the file A in integer mode and add all the numbersDo same with B and subtract the sum… this is your numberCaution: integer overflow might occur so you can use linked lists to store the sum and compute the difference! |
answer: @Anon – your solution seems to assume the data is ordered the same way in both files ?ex-oring each character in one file and then ex-oring the results in the two files would give the differing character…O(n) time complexity with minimal space complexity |
question :
serialize binary tree |
answer: Do something similar to Breadth-First-Traversal. For each node assign an integer key that should be serialized along with the nodes data. Start with 0 as key for the root. For each node with key x, push it’s left child (if it exists) with key 2x+1 and it’s right child (if it exists) with key 2x+2. The key uniquely identifies position of the node in the tree. |
answer: Record both pre-order and mid-order sequence |
answer: Do the array representation of the tree: children at 2n and 2n+1 |
question :
1. Find common elements between two arrays of integers. 2. Find cycles in a graph. 3. Efficiently find duplicate elements in an array of numbers with bounded entries (for example, elements are between 0 and 99). 4. Reverse word sequence in a string inplace. 5. Efficiently find all Pythogorean triplets in a given array of integers. 6. Find all anagrams in a list of words. 7. Set operations. |
answer: @1: Can you first mergesort the two arrays, and then do the following? That’ll be nlogn runtime? I haven’t tested it out…int i=0, j=0;while ( i<sorted_array1_size && j<sorted_array2_size ){ if( sorted_array1[i] < sorted_array2[j] ){ i++; }else if ( sorted_array1[i] > sorted_array2[j] ){ j++; } else { //must be equal printf("Common element: %d\n", sorted_array1[i]); i++; j++; }} |
answer: for #1 you just have to hash the first array and then if(contains) the hash table against each element of the second arrayO(n) # of comparisons |
question :
List all anagrams in a file. Assumptions: case-insensitive, a-z characters only, one word per line. For example, if the file contains dog, cat, ddd, goo, act, god — output dog, god, act, cat |
answer: Thankfully I was taking a theory course and one trick used in the course was "encoding" programs as a large natural number using product of primes.1. Adapt the encoding as follows — generate the first 26 primes and assign a prime to each letter2a. For each word, take the product of each letter’s prime. So #(act) = 2*5*prime(t)2b. As you can see, #(cat) = 5*2*prime(t) = #(act)3. Insert a handwavey argument about inserting the number/word pairing into a HashMap<Integer, Set<String>> |
answer: Sort the words. Anagrams appear next to each other in the sorted list. |
answer: Sorry, sort the letters in each word, then sort the words. Anagrams appear next to each other in the list. For example the sorted list for the input would be:actactddddgodgogoo |
answer: Thanks for sharing BillFor this set of input, the expected output should contain only [cat, act, god, dog]. I’m curious to see what "next steps" your algorithm will perform to provide this expected output |
answer: You keep track of the mapping from the sorted word to the actual word in a pair, for example:[act, cat][act, act][ddd, ddd][dgo, god][dgo, dog][goo, goo]Then you go through this list and count if you have a duplicate entry or not. If you do, like for act, you print out those duplicate entries: cat, act. |
answer: Bill, your algorithm is O(n*log(n)) while the candidates would be O(n) – provided he uses a decent hash function |
answer: donutello,bills algo is not n log n it is n*log(k)where as candidates algo is n * k again (multiplications for each word)where k = length of the longest wordon top of that calculating primes is expensive anywayI would go with bills answer |
answer: Bills algo is nlogk + nlgn.After sorting the k letters for n times you also have to sort the n words. |
question :
We have numbers from 1 to 52 that are put into a 51 number array, what’s the best way to find out which number is missing? |
answer: my answer was to sort the array and use a boolean variable with a while loop that will exit when the number is not equal to the previous number plus 1 |
answer: The above answer is a typical answer or brute force technique, which anyone could answer. What they are looking for is probably how good you are at math and algorithms. My answer would be:1) Calculate the sum of all numbers stored in the array of size 51.2) Subtract the sum from (52 * 53)/2 —- Formula : n (n+1)/2.The result of subtraction is the answer for this question. |
answer: Just want to add some comments to Babji Chetty’s answer.To calculate sum of complete sequence of 1 to 52 is used arithmetic progression sum formula. s = n(2a1+d(n-1))/2, where d is the step. Using this formula you can calculate sum of full sequence even if increment step not equal to 1. |
question :
Given an array of integer in which all numbers occur even times except for one number occurs odd times, find it. |
answer: i) sort array (n or nlogn at the max). go through array and count #occurrences for each num. (memory: null, just 1 var)ii) if lots of memory then use hashing |
answer: xor all elements |
answer: keep on adding the elements,wherever the sum becomes odd that number is the odd one. |
answer: "keep on adding the elements,wherever the sum becomes odd that number is the odd one."Fails on int array[] = {2, 2, 4, 3, 3} |
answer: xor is the correct answer |
answer: Can explain the XOR answer pl. thanks |
answer: if you xor an number with it self you get 0 ,if you xor a number with 0 you get the number it self,eg 2,2,4,3,32^2 = 0 0^4 = 4 4^3= 7 7^3 = 4 and the answer is 4, |
question :
Write an algorithm to return the intersect of two arrays. |
answer: /// <summary>/// Finds the array intersection points./// </summary>/// <param name="firstArrayList">The first array list.</param>/// <param name="secondArrayList">The second array list.</param>/// <returns></returns>public static List<object> FindArrayIntersections(List<object> firstArrayList, List<object> secondArrayList) { var intersectionPoints = new List<object>(); foreach (object firstObject in firstArrayList) { foreach (object secondObject in secondArrayList) { if(firstObject.Equals(secondObject)) { intersectionPoints.Add(firstObject); } } } return intersectionPoints; } |
answer: Martigan’s answer should generally work but it has an O(n^2) running time. There’s a better way using hashtables. Create a hashtable with all the elements in the first list. Then go through the second list, hash each entry, and compare to the first table. If there is a collision then the entry exists in both lists and should be added to the intersection list. |
answer: In my interview, I first gave the first answer above, and then I gave the 2nd one mentioned above :p |
answer: if no additional space is available for hash tables then the best time complexity seems to be n Log n + m Log m. Sort each array independently and then compare. |
question :
All questions asked were within normal types of interview questions. |
answer: Their phrasing of the questions were amateur at best. |
answer: I also had the same experience. If they only want to hire people who can answer questions like these over the phone then I don’t think they’re the kinds of people who are pleasant to work with. I don’t think professionals would fit in at Amazon. |
answer: Had the same experience. Most of my interviewers were rude, arrogant and inconsiderate. Process partly alright but in portions very awkward and not thought through. |
question :
First phone screen: Print all the nodes of a tree in reverse level order (ie print all the nodes at the leaves first, then print the nodes on the level above the leaves, and then eventually work your way to the top). |
answer: With no additional restrictions, this sounds as though it is simply a post-order traversal of the tree. |
answer: The above answer is wrong, consider the tree below: 10 / \ 5 15 / \ 12 25The post order traversal is 5, 12, 25, 15, 10 but the answer should be 12, 25 (or 25, 12), 5, 15 (or 15, 5) and 10The correct solution would be to do a BFS from the room using a queue. After visiting a node, add it to a stack and continue. When done the traversal, loop the stack popping elements and printing to screen. |
answer: Do a level order traversal of the tree and reverse it. Am I missing something, or is the reverse part in there just for kicks? |
answer: Do an in level order traversal and place each node visited into a stack. Then, pop each element from the stack. The elements will pop out in the reverse order. |
question :
Second phone screen: Implement a function to determine if a string is a substring of another string. |
answer: public static boolean isSubString(String srcStr, String subStr) { char[] srcChar = srcStr.toCharArray(); char[] subChar = subStr.toCharArray(); int m = srcChar.length; int n = subChar.length; for (int i = 0; i < m – n + 1; i++) { int k = i; for (int j = 0; j < n; j++) { if (srcChar[k++] == subChar[j]) { if (j == n – 1) { return true; } } else { break; } } } return false; } |
answer: private static boolean isSubstring(String sup, String sub) { char[] a = sup.toCharArray(); char[] b = sub.toCharArray(); for(int i = 0; i<a.length ; i++) { if(b[0] == a[i]) { for(char c: b) { if(c != a[i++]) return false; } return true; } } return false; } |
question :
Given a list of n numbers. All numbers except one are unique. Find the number with duplicate entry. |
answer: I gave an nlogn solution, where I said we will heap sort / quick sort the array, and then do a linear traversal to find out the duplicate entry. The interviewer was okay with the solution, and then she asked me code it, and then to write test cases for it. |
answer: How about using hashtable? |
answer: Use the function n(n+1)/2 = sum(0,n). Sum up all of the numbers in the array. Subtract the number from the function from the number in given by the sum. That will be your duplicate entry.public static int dupeNum ( int [] array ){ int arraySum = 0; int arraylength = array.length; int knownSum = (arrayLength * ( arrayLength + 1 ) ) / 2; for (int i : array ){ arraySum += array[i]; } return (arraySum – knownSum) ;}Should be O(n). |
answer: ^^ person who replied above: Your solution fails if the numbers aren’t sequential – for all you know, ‘a list of n numbers’ could be ‘n’ random numbers |
answer: Merge sort it and then it iterate through the list. This takes nlogn time.public in getDuplicate(List<int> list) { List<int> sortedList = Mergesort(list); for(int i = 0; i < sortedList.length-1; i++) if(sortedList[i] == sortedList[i+1]) return SortedList[i]; Throw exception; } |
answer: take XOR of all the numbers.You will get the sum with out the duplicated number.(sum of all n – above sum) will give you the number |
answer: put the numbers into hashmap while traversing the list. Before placing the key into hashmap check whether it is null or not. if it isnot you’ve found it. worst case O(n). extra hashmap in the memory. |
question :
Extract the N largest floating point numbers from a large file of floating point numbers. |
answer: To do this efficiently you need to keep your largest number list sorted and you only need to make comparisons to the smallest number in the list. Remember that sorted list insertion is O(lg n). |
answer: its about extracting from file of floating point numbers.so have to use scanner to extract floating point numbers and add it in to the list or arrayand sort it, using Collections.sort or Arrays.sort function of JAVA. |
answer: maxheap will do the work |
answer: #define N 2#define SIZE 3int tab[SIZE];int max;int sovj;for(i=0; i<N ; i++){ max=-MAXINT; for(j=0; j<SIZE ; j++) { if(max<tab[j]) { max=tab[j]; sovj=j; } printf("\n j: %d", sovj); tab[sovj]=-MAXINT; }} |
question :
Given a list of integers, some of which may be negative, extract the pair that sums to the largest number. |
answer: The naive solution is O(n^2). The trick is to sort the list in O(n lg n) then pick the two largest numbers from the front. |
answer: you can get the largest two number in O(n), right?sum those two numbers up. |
answer: Whoops, I wrote the wrong question. Here’s what I meant to say: given a list of integers, find a pair that sums to a given value. |
answer: Keep a list of integers, and set it to 1 if they are in within the list.for (int i = 0; i < n; ++i) dp[array[i]] = 1;for (int i = 0; i < n; ++i) if (dp[S – array[i]] && S – array[i] != array[i]) print S – array[i] and array[i] because they sum to SThis is the subset problem. This is O( n ), but requires O( S ) space. |
answer: @bleh: I guess the solution will work if all the elements are +ve, in this case however the elements are negative. So probably we can use hash instead of arrays. |
answer: if both hashing and the subset solution aren’t good enough -1. Sort the array o(n) or o(nlogn) – pick the one you can sell2. Have two pointers – one at the end and the other at the beginning3.a. If the sum is less than S increment the one in the beginning3.b. If the sum is greater than S decrement the one at the end3.c If the sum is S – you are done3.d If the two pointers have met or crossed over – you are done |
answer: Amazon really loves dynamic programming eh? I’ve come across many interview questions with the knapsack and coin-change problems |
answer: #define SIZE 3int tab[SIZE];int sum;int max=-MAXINT;int sovi, sovj;for(i=0; i<SIZE ; i++){ sum=tab[i]; for(j=i+1; j<SIZE ; j++) { if((sum+tab[j])> max) { max=sum+tab[j]; sovi=i; sovj=j; } }}printf("\n i: %d j:%d", sovi, sovj); |
question :
What would you do if senior management demanded delivery of software in an impossible deadline? |
answer: Give them the choice of reduced scope, more resources, or changed dates. They can only pick 2. |
answer: It is possible to keep scope, resources & timeline (dates) unchanged, but compromise on quality. This will impact team retention, especially the stronger engineers on the team, over the longer run.The leadership team must understand the consequences. |
question :
Was asked to describe what I would do in a situation where I didn’t know the correct Amazon approach for a problem. |
answer: I stumbled through this one a bit before realizing that the interviewer was trying to prompt me to say that I should look to other teams and colleagues outside my team for an answer. |
answer: Can someone provide some kind of questions that they have faced for program management job at amazon in the vendor management area. I have a interview lined up and would like to take suggestions from experienced folks out here..I will post the kind of questions that i come across once done.. |
question :
How would you handle an employee who showed up to work drunk? |
answer: I would kick his ass and boot him to the curb |
answer: Partner with another manager and ask the employee if he feels okay. Check for obvious signs. If both agree for safety, ask the employee to join you in a quiet place off the floor, and seek to understand why his behavior and work performance seem ‘off’ today. Contact HR. |
question :
Given two (huge) sets, what is an efficient way to find their intersection? |
answer: hey can you please share the answer with us?I have 2 ans:1. sort both the sets and iterate to find intersections. (nlogn)2. use hash. (n)Please let me know if it could be done in a better way.Thanks! |
answer: I think "huge" is an indication that using a hash set approach would be untenable, the idea being that you’d run out of RAM. The n log n approach seems correct to me. |
answer: Dont u think nlogn is larger than n since in data structures, the base of the log is always 2 |
answer: he meant untenable in space. in time of course you cannot beat the hash |
question :
What is something that really bothers you? |
answer: I gave my answer about "inequity among peers" but that seemed to bother the interviewer! |
answer: I had a similar reaction! I brought up that I didn’t enjoy office politics and that one of my major work standards is that within the company one should row into the same direction, external competition as long as one doesn’t overlook the need for collaboration, co-creation and strategic alliances.I feel these are similar categories as they don’t seem to enjoy discussions of their "equality" approaches and prefer arrogance and pushy internal competition from the impression of my interview. I didn’t perceive them that way b4hand. Very much changed my mind though.(Plus: EOE and their lack thereof is an issue over here in Europe at least in the press.) |
answer: "external competition is OK" that should have read… |
question :
Write a program for creating Huffman Coding for a set of characters given its frequency table. |
answer: You need to use Min Heap. Basically you need to extract twice (2 least frequency chars), combine the letters and add it back to the heap. |
answer: cs.nyu.edu/~melamed/courses/102/lectures/huffman.ppt |
question :
If you had 5,623 participants in a tournament, how many games would need to be played to determine the winner |
answer: Before I could figure that out, I’d need to know whether the # of participants represents the number of individuals on larger teams, or the number of teams |
answer: A specific numerical answer can be given, but there are multiple ways the tournament can be setup, for example, are there play-in games, byes, etc. I would think the question is being given to a manager to see how they think and process, and then come up with a specific numerical answer, as opposed to just a math problem. |
answer: It can be just one game. A huge mock battle. |
answer: 5,622. Assuming it is a single elimination tournament. All teams lose one game except the champs. It’s always # of teams – 1 |
answer: if each team plays until it loses in one(team)-on-one(team) contests, the answer is ln(5623)/ln(2) |
answer: Assuming it is a simple process of elimination, it takes 5622 losers to get 1 winner from 5623 participants. So, it would require 5622 games. |
answer: Assuming it is a simple process of elimination, it takes 5622 losers to get 1 winner from 5623 participants. So, it would require 5622 games. |
answer: if it’s a 1:1 type draw, then # rounds = (5623)**x where x is base 2. a good answer is between 12 and 13 rounds.2**12 = 4096 so I’d draw up 13 rounds and give out 1,527 byes. |
answer: There is no true answer as the question is very open ended.The interviewer is probably looking at task delegation, management and creativity skills. |
answer: One |
answer: One. Obviously. |
answer: One game, all players participate. |
answer: If participants equal number of teams involved, think power of 2. |
answer: The interviewer is not looking for the right answer because there can be many. What he/she is looking for is your logical approach in solving the answer. So you could start by probing more is first I would like to understand if 5,623 participants represent the number of team or individuals. Then ask the next logical question based on the answer. |
answer: Everyone who didn’t ask a follow up question except Mike is right.The question says, "if YOU had …". This requires no follow up questions, because YOU should decide how YOU are going to operate YOUR tournament. Why would Mike or any of the others think it’s someone else’s job to organize his/her tournament. |
answer: Oh just a follow up. My tournament would be held in the top of a hardly dormant volcano. Everyone would get a backpack full of grenades and the first one out of the crater without dying wins. That makes 1 game.Also, I think most participants who got out of the volcano alive would consider themselves winners, but only one would get to keep the gold plated dancing chiquita banana.Yipee!!!! I’m right too! Take that Mike! |
answer: it’d be one game if it was a battle to the DEATH |
answer: I agree with Nancy there is no strict answer to this question it is all about problem solving. First thing to do is to get more information, if it is not forthcoming then make assumptions, as an interviewer I would not be impressed if the candidate didn’t ask for more information, although I probably would not supply any more.Then looking for a logical (and humane) answer which is substantiated with appropriate reasoning. Ie number of people on a team, game being played, what is required to win a match, are there several games in a match? knockout style tornamant sounds like a good approach. |
answer: I agree with Mike. Just show the interviewer how you think and how you will tackle the problem in a colloborative environment |
answer: 1 |
answer: I agree with the very first response. Many of you are perhaps making the assumption that this is a one-on-one tournament such as singles tennis. Isn’t it possible the question could refer to a soccer or basketball tournament where there are multiple players on each team? That would certainly bring the number of games to be played down considerably. |
answer: I’d give an approximate answer, stating my assumptions. The question asked is not the number of rounds (2 people per game: log base 2, giving approximately 13 rounds with everyone playing at least one game ) – it’s the number of games. So, if two people per game, then it’s the sum of 5623/2 + 5623/4 + 5623/8 + 5623/16 + … The limit of this is not something I know off the top of my head, but it’s less than 5623. Also, interestingly, you need to account for the original number being odd. That could be accommodated in a number of ways, none of them straightforward. |
answer: 5622 … if based on elimination between 2. |
answer: I personally agree with most of you. If you read the posts here, you see all types of answers. Some say "1". Short and simple rules to a simple game. Others have posted all types of formulas and methods to figure out a process. The answers here are all a good example of different minds using different means to find an end. Those different answers are what a good interviewer would be looking for. If the job needs a person that is logical and takes time to plan things out, or perhaps someone that needs to think fast on their feet. That kind of question could come in handy for any kind of interview in my opinion. |
answer: 1 |
answer: I think the interviewer is asking you to ask for more information, ask three qualifieng questions to be exact in order to show you have the probing skills to fully understand a customers situation or company problem and have the ability to ask the appropriate questions to or to get the help to solve. Question 1) How many players are allowed per round? Question 2) Is there a time restriction on these rounds? (Daylight or Night as well) Question 3) Are there going to be different classes for the golfers? Are we taking handicaps into consideration? I guess there could be more questions but chances are the interviewer would stop you after the third question. |
answer: The correct answer is:"I didn’t come here to play bulls**t games for 8 hours, you Mac-slinging hipster. Ask me a real question." |
answer: 5622………………………………assuming single elimination |
answer: 5623 is a prime number. Good luck dividing into even teams. Also, thereis no use of the word "minimum" in the original question. This question isa good example of a problem with no absolute answer. If I were to ask thisof an interview candidate (which I wouldn’t because I think subjectivequestions are mostly a waste of time for everyone involved), I would lookfor someone who can:A) Ask questions to pin down a few details.B) Formulate options.C) Suggest options with recommendation and take feedback.D) Execute (pretty hard to demonstrate in the 10 minutes max I’d give this).p.s. I’d hire chapped. Good answer! |
answer: Depends on the numbers of players per team. |
answer: ‘Excuse me, I’m just waiting for excel to open and my math wiz buddy in accounts to pick up to verify my calculation. I’ll get back to you in two minutes with the answer.’ |
answer: ‘Excuse me, I’m just waiting for excel to open and my math wiz buddy in accounts to pick up to verify my calculation. I’ll get back to you in two minutes with the answer.’ |
answer: I would try and be creative and put my suggestions in front of them while I give them a reason for all the options that I choose. For instance, I’d say I would create 5 levels for each game as adding more levels makes the game more challenging and interesting. I wouldn’t want to set up too many games as it would require a lot of overhead using up a lot of resources for organizing large number of games. Hence, in each round I would eliminate 20 participants. That would make 100 players getting eliminated after every game. After every 10 games, I would allow all the eliminated contestants to battle it out and 15 can re-enter the game as the eliminated ones would get a chance to observe, learn, refresh and get a second chance… (The interviewer might stop me eventually before it gets too long).Even though my answer was too long, I think I would show them how my logical thinking works. They would see that I am thinking aloud and in the end all that matters is how we approach the problem rather than giving them a vague answer with no reasoning. |
answer: Oh and I agree with Toasty, I would hire chapped I like the way they think. |
answer: Oh and I agree with Toasty, I would hire chapped I like the way they think. |
answer: i dont know how everybody else thinks butI divided by two with an extra game for when the number is odd and came up with 5627. the question was straight forward, " How many games"…. |
answer: I would have been startled as well, just reading it. Congrats on keeping your calm!My intuitive answer would have probably been:Game theory – 1 or rather none – when it’s a battle to death everyone loses, even the winner (last man standing, howling at the moon).I would have likened it to the company and customer situation – in good company EVERYONE is a winner (win-win scenario).Good luck with your endeavors! |
answer: 1. I think, this question is for a management position. The size of team is given as a too big random number. One cannot control a team of 5627. Divide them in a measure size, e.g size of 10 or 20 (any measureble size). With 10, there will ve 563, which can be further divided into 10, leading to apx 57. that can be futher divided into 10, leaving it to 6 teams. proformance/ goals can be set and can be evaluated later.2. or do a marathon. |
answer: None. Our PC world demands everyone gets a trophy. |
answer: *********************Keep in mind the position, Nathaniel is right. YOU are organizing the tournament, make a rational decision and describe it. Your answer should be formulated to convey a skill.For example I might suggest something like this:1 on 1 round robin, 5,623 players, SUM(1+2+3+…+5621+5622) gamesQuick and simple, shows some knowledge of algorithms but not very practical.The 1st participant plays 5622 others, the 2nd plays 5621, until the 5622nd plays 1 (5623rd participant). Notice you don’t add 5623. Participant with the most wins is the champion. |
answer: Supposed it is a single elimination.should be 5626 gamesbecause the first row would be 5623/2 = 2811.5which means 1 person must be going to the next round to competetherefore we will have 2812 contestantsthen the second row would be 2812/2 = 1406the third row would be 1406/2 = 703(odd number which means the one of them is going to the next round without a fight. ect… |
answer: I believe I would have responded with "Is that how many applicants there are for this job?" Followed by "One game, one victor." |
answer: Before answering you should read the interview report this question is linked from, where the question is explained in more detail — """If you had 5,623 participants in a tournament, and each participant had to play games until he/she one or lost, and every game had a winner and loser, how many games would have to be played in order to determine the winner of the tournament"""So it’s pretty unambiguous: Participants are individuals; the tournament is single elimination; games involve just two parties (a winner and a loser.)The question doesn’t ask about the number of rounds involved, nor about timeframe. Just the sheer number of games.So we’re left with an answer of 5622 games (because every game has one and only one loser and 5623 – 1 participants need to lose for there to be a single participant left as the winner, so that’s how many games there must be.) |
answer: Assuming in each game "n" people participate and there is just one winner in a game. If N is the total number of people (in this case 5623), then the approximate number of games would be:log(N)/log(g) -1 |
answer: After each round, you would have half the number that started the previous round; except if it were an odd number it would he half + 1. So 13 rounds.2812 11406 2703 3352 4176 588 644 722 811 96 103 112 121 13 |
answer: It is far simpler than you guys are making it out to be. In ALL single elimination tournaments there is one less game than the number of participants. Because in every game 1 team gets eliminated. And at the end 1 team has to be left standing. |
answer: This will be a detailed explanation.Since they’re asking for a tournament, that means one on one matches, and eliminations of ‘participants’ or players. With such a large number doing a round robin style tournament would not be very efficient, as every player would have to play every other player, ((N-1)^2)/2 =15,803,442 matches. I would first start to get more details of the tournament. If it were up to me to design the tournament and easily determine the number of matches, I would go with single elimination bracket because since its based on power of 2.Contrary to what what Bob InNorCal did, you dont start halving the at the beginning with 5623, because its not power of 2. You will get to a point where there wont be even numbers, and BYEs will have to be given, it would be unfair to give byes out at the end or middle of the tournament, players would complain that others got BYEs and they didnt.Detailed Explaination:In a single elimination bracket, the brackets end with 1 match between 2 players, then 2 matches and 4 player, and eventually for this tournament, 4096 matches between 8192 players. But since we dont have 8192 players, there will have to be BYEs which wont count as matches. In this case we’ll have to use a 8192 single bracket, with the first 4096 players spread every other position then the last 1527 players spread evenly throughout the bracket and the remaining 2569 positions are BYEs (4096 + 1527 + 2569 = 8192). Here are how the rounds look like:A – 1527 matches, (4096 matches was suppose to happen, but 2569 BYEs are no counted)B – 2048 matches,C – 1024 matches,D – 512 matches,E – 256 matches,F – 128 matches,G – 64 matches,H – 32 matches,I – 16 matches,J – 8 matches,K – 4 matchesL – 2 matches,M – 1 matchFrom round B-M, its (2^12)-1 = 4095, so with Round A, its 4095+1527=5622.The calculated answer 5622 is one match less than the number of participants.However, just because its easy with single elimination to determine the number of matches, does not mean that it is what they initially asked, conversing with the interviewer for more details of the tournament is important. If the interviewer said it was a double elimination tournament then a player would have to lose twice in the bracket to be eliminated from the tournament. Depending on the number of players and the placement of the BYEs, then calculating the number of matches in a true double elimination maybe difficult. Also in Double Elimination, the winner maybe won by someone without a loss or with 1 loss, the winner without a loss means one less game. |
answer: it is assumed that the competition is a head to head knockout competition like wimbledon. the only correct answer is 5,622. the quickest and smartest way to get that answer is to see that in a knockout tournament every body loses once and only once, except the winner. in every match, one person loses. therefore the number of matches required equals the number of players minus 1.PaulO, Jordan, madhur, simplebrain and key2success you are all hired! |
answer: How many games are played? Well all of them of course, how else do you find the winner. |
answer: It need only one game to find the winner |
question :
How do you insert into a binary tree? |
answer: You find the spot to insert by traversing to where you think it is located. Then, you add it there if you don’t find it. The complexity is O(log n) |
answer: was it a general binary tree or bst? |
question :
Find the most common "3 page path" on a website given a large data log. |
answer: What’s the complexity of your algorithm? |
answer: Quick and dirty: * Build a list of url/timestamps per user * sort each list by timestamp * iterate over each list o for each 3 URL sequence, create or increment a counter * find the highest count in the URL sequence count listforeach(entry in parsedLog){ users[entry.user].urls.add(entry.time, entry.url)}foreach(user in users){ user.urls.sort() for(i = 0; i < user.urls.length – 2; i++) { key = createKey(user.urls[i], user.urls[i+1], user.urls[i+2] sequenceCounts.incrementOrCreate(key); }}sequenceCounts.sortDesc()largestCountKey = sequenceCounts[0]topUrlSequence = parseKey(largestCountkey)found on this site:http://stackoverflow.com/questions/2991480/most-frequent-3-page-sequence-in-a-weblog |
question :
What’s the biggest problem you see with our company? |
answer: This wasn’t just a test – they really did have a problem they wanted me to solve. |
answer: I have seen several leadership level jobs advertised relating to a newly formed team. I would love to talk to someone to learn more about the status of the team, it’s mission, etc. Is it possible to speak with anyone inside Amazon or a recruiter? So far, I’ve not found a contact via internet search. Any suggestions for being able to ask questions directly of HR or a recruiter regarding a set of job openings? |
question :
Implement a function to validate whether a given binary tree is a BST (i.e. write an isBST() function). |
answer: I came up with a recursive solution something like this:boolean isBST(TreeNode node, int min = INT_MIN, int max = INT_MAX) { if (node != null) { if (node.left != null && node.left > max || node.right != null && node.right < min) { return false; } else { return (isBST(node.left, min, node.value) && isBST(node.right, node.value, max)); } } else { return false; }} |
answer: How come this function never returns true?And why would you need min and max? |
answer: Ok, so I should have spent a little more time posting this (I was admittedly rushing through it so I could get access to more questions/answers). Here’s a revised version that should hopefully make more sense:boolean isBST(TreeNode node, int min = INT_MIN, int max = INT_MAX) { if(node == null) { return true; } if(node.value > min && node.value < max && IsValidBST(node.left, min, node.value) && IsValidBST(node.right, node.value, max)) { return true; } else { return false; }}The main change is that I decided to avoid checking the children of the tree in the body, and leave it to recursion to take care of that. Thus, we just have to look at the current "node" and that’s it… the constraints will be handled by passing min and max down.@Alexander – in response to your questions, the original function does in fact return true, if the condition (isBST(node.left, min, node.value) && isBST(node.right, node.value, max)) happens to evaluate to true. Finally, the min and max values are required because a BST requires that each value in the left branch be smaller than ALL parent values on that branch (and similarly for those on the right branch being larger). Another way of saying this is that the entire left tree of any node must be smaller than the node’s value, and the entire right tree must be larger than the node’s value. Thus, in a recursive solution, you have to have a way to pass down the upper and lower bounds to the lower levels of the tree, otherwise the third level won’t be able to check whether it’s smaller/larger than the root two levels up. That’s why we pass down the min and max values.Hope this helps. |
answer: boolean isBST(TreeNode node){ if(node.isLeafNode( )) return true; else { if(node.value < node.leftChild || node.value > node.rightChild) return false; else return (isBST(node.leftChild) && isBST(node.rightChild)) }} |
answer: traverse in order and see if they r same |
answer: @Alexander – in response to your questions, the original function does in fact return true, if the condition (isBST(node.left, min, node.value) && isBST(node.right, node.value, max)) happens to evaluate to true.=============Those are just two function calls and the function never returns true. Alexander is right – you are missing a terminating clause in your recursion. |
answer: Forgot to add – your second solution is correct since it returns true. |
answer: // For +ve number OR use INT_MIN instead of -1(s)bool BinarySearchTree::validate() { int minVal = -1; int maxVal = -1; return ValidateImpl(root, minVal, maxVal);}bool BinarySearchTree::ValidateImpl(Node *currRoot, int &minVal, int &maxVal){ int leftMin = -1; int leftMax = -1; int rightMin = -1; int rightMax = -1; if (currRoot == NULL) return true; if (currRoot->left) { if (currRoot->left->value < currRoot->value) { if (!ValidateImpl(currRoot->left, leftMin, leftMax)) return false; if (leftMax != currRoot->left->value && currRoot->value < leftMax) return false; } else return false; } else { leftMin = leftMax = currRoot->value; } if (currRoot->right) { if (currRoot->right->value > currRoot->value) { if(!ValidateImpl(currRoot->right, rightMin, rightMax)) return false; if (rightMin != currRoot->right->value && currRoot->value > rightMin) return false; } else return false; } else { rightMin = rightMax = currRoot->value; } minVal = leftMin < rightMin ? leftMin : rightMin; maxVal = leftMax > rightMax ? leftMax : rightMax; return true;} |
answer: // using inorder traverse based Implbool BinarySearchTree::validate() { int val = -1; return ValidateImpl(root, val);}// inorder traverse based Implbool BinarySearchTree::ValidateImpl(Node *currRoot, int &val) { if (currRoot == NULL) return true; if (currRoot->left) { if (currRoot->left->value > currRoot->value) return false; if(!ValidateImpl(currRoot->left, val)) return false; } if (val > currRoot->value) return false; val = currRoot->value; if (currRoot->right) { if (currRoot->right->value < currRoot->value) return false; if(!ValidateImpl(currRoot->right, val)) return false; } return true;} |
question :
Describe what happens between the time a person types in "www.amazon.com" and they see the web page on their computer. |
answer: At a relatively high level (that is, glossing over routing table lookups, packet retransmits, load balancers, etc):Browser performs DNS lookup of www.amazon.com to resolve IP address.Browser submits HTTP request (over TCP over IP) to server with IP address returned above.Browser waits for HTTP response (again, over TCP over IP) from Amazon server.Once the original HTTP response is complete, browser begins layout and starts requests for additional content (embedded images, video, etc). The page can display to the user while these requests are outstanding.As content requests come in, browser inserts content and displays to user. |
answer: You probably also need to talk about as to what happens in the back-end1. The httpd gets the request2. Correct page is called.3. The page looks at the cookies and the user’s ip, and determines the recommendation and such, so the content is geared toward the user.4. Make DB request to get information about the products.5. so on |
question :
What is deadlock |
answer: In simple terms, a deadlock occurs when two threads each lock a different variable at the same time and then try to lock the variable that the other thread already locked. As a result, each thread stops executing and waits for the other thread to release the variable. Because each thread is holding the variable that the other thread wants, nothing occurs, and the threads remain deadlocked. |
answer: I faced a situation at work when our code after opening a DB connection was getting into exception without closing the DB connection. Under high load the number of requests for DB connections were too much and could not wait for DB to timeout stale connections. Result was DB locks |
question :
How would you optimally sort an unsorted random list of numbers by using multiple computers. |
answer: quick sort or merge sort would do. They can be easily parallelized. |
answer: Along with quick sort and merge sort, we can also do counting sort if:i) The elements are integers.ii) If the range of elements i.e. ints is limited (say k).Complexity: O(n+k.) |
question :
Given a set of N numbers, assume that you have the set of numbers from 1 to N+1, with the exception of one number. How do you determine what number that is? What is the complexity of your solution? |
answer: Two Step Process -1) Sum of N Numbers Formula – (N*N+1)/2 [Complexity O(1)]2) Iterate over the given N-1 numbers and calulate the sum [Complexity O(n)]Subtract result 1 – result 2; this gives the missing number! |
answer: How about binary search on a sequence ????This would take O(log n) to find … |
answer: Binary search on a sequence is O(log n), but you are assuming that you have been given an ordered set, which is not specified. The sort on the set will most likely be O(n log n). |
answer: binary search in general meaning, not binary search on sorted list |
answer: Binary search only works on a sorted list. It doesn’t work anyways since you won’t know what you are searching for. The correct answer is to iterate through the sorted list and look for the missing value, which takes n time. |
question :
There is an array of numbers, containing the integers 1-n, how can you find the sum of the numbers in that array? |
answer: n(n+1)/2 |
answer: what if duplicates r thr or some number missing? |
answer: wat a stupid ques..just traverse the array and add up every number |
question :
I had a difficult question about a cuboid composed of smaller cubes. How many cubes are there where exactly two faces of the cube are exposed? |
answer: So a small cube in the corner of this cuboid would have exactly 3 faces exposed, and a cube in the middle would have only 1 face exposed. So the trick is to count the edges since a cube on the edge would have two faces exposed. |
answer: Just thinking about this question in my head, I came up with the answer as being:12 *(n – 2)where n is the total number of smaller cubes along one edge of the cuboid. |
answer: If there are ‘n’ small cubes in the cuboid….(1/3)n of the cubes will have exactly 2 faces exposed. Eg: if there are 48 small cubes, 16 of them will have exactly 2 faces exposed. |
answer: Darpan is wrong.The cube could never be made of 48 cubes first off.2 across = 8 total cubes3 across = 27 total cubes4 across = 64 total cubesThe formula would be (using a set of 64 cuboids):Find the 3rd root of the number of total cubes. This is how many cubes are on an edge.(3rd root of 64 = 4)Subtract 2 from that to account for corner cuboids (4 -2 = 2)Multiply by the number of edges (2 * 12 = 24)24 total cubes with 2 faces exposed |
question :
How would you find the pairs of numbers that added to some specific number in an array. |
answer: i program in java..so i will talk from the arrayLists perspective.suppose we want to find out a+b = 123;for(int i=0; i<arrayList.size();i++){int a = arrayList.get(i);indexOfComplimentaryNumber = arrayList.indexOf ( 123 – a) ;the indices of pairs are (i, indexOfComplementaryNumber).As you get into more specifics, such as uniqueness of numbers etc., you can start removing elements visited, and shorten the arrayList. But sorting the arrayList and then doing the above is inefficient, in large collections.. say >2000 records.but below that, sorting and above operation is efficient.you must play with different possibilities. |
answer: Your answer (using arrayList.indexOf(…)) is worse than sorting. Sorting is O(log n), finding an item in an unsorted array using ArrayList.indexOf is O(n).Given an unsorted array input (e.g. int[] input), sort it using Array.sort(input) … this is O(log n).Start at input[0] of the sorted array and calculate it’s complementary value. Go to the end of the array and iterate backwards until you find the complementary value or less. If it’s less repeat for input[1] and iterate backwards from the previous last item … keep going.This is at worst proportional to n/2, ie O(n). |
answer: I realize I wasn’t totally clear in my first paragraph … searching for the complementary value of one item is O(n), but you have to the search for (at worst) every item, so your solution is O(n^2). |
answer: Duh – sorting is O(nlog n) … |
answer: Using hashing, this can be done in O(N).store the n/2 mod i in the corresponding hash bucket. Now check the each hash bucket and you are done. |
answer: sort the array (o(n(log(n))and take two pointers at both the ends say p1 and p2if p1+ p2 < n( say) -> move the pointer p2 by 1 and add to checkif (p1+p2) > n -> move the pointer p1 by 1 and add to checkif (p1+p2) = n ->print the pair [traversal takes o(n)]finally thus can be done in o(n) |
answer: I will not waste o(nlogn) in sorting the array.Instead assuming that the sum we looking for is k, i will divide the array into 2 arrays.First array will contain all values which are less than k/2Second array will contain all values > k/2This is bcoz in a sum if one number is less than k/2, the other has to be larger.I will iterate over the smaller array of the 2 since they would rarely be equal.For each x in array 1, i will find the k-x in array 2.Complexity will be O(n). |
question :
Design and implement an algorithm to determine if a binary tree is symmetric. |
answer: Each node in a binary tree can be mapped to a binary string encoding its position in the tree. For each level below the root, the string should consist of a 0 if the node requires a left traversal or 1 if a right. This is important because a bit string s and its inverse ~s will represent symmetric paths down the tree.A solution to this symmetry problem would perform a tree traversal and, at each node in the traversal, encode the path as described above. Then, negate the path to generate ~path and fetch that node. If it exists and is identical to the original node, continue the traversal – otherwise, we stop (not symmetric). |
answer: symmetric(t) = reversed(t.left,t.right)mirrored (t1,t2) = mirrored(t1.left, t2.right) && t1.data=t2.data && mirrored(t1.right, t2.left)inspired from : http://stackoverflow.com/questions/1482822/how-can-we-find-given-two-binary-trees-that-they-are-equalgro.eeei@jzw (reversed) |
answer:
This post has been removed. Please see our |
question :
Was given a homework question(2days): Program using a language of your choice the following assignment, given a file of sorted strings (one string per line, example file was given) sorted according to some unknown alphabet, recover the order of characters of this alphabet. |
answer: Answer: used c#, problem is related to building a transitive closure, so I used a recursive algorithm to fill a relation matrix between characters (M(i,j)= 1 if abc(i) larger abc(j) and M(i,j)= -1 if abc(i) smaller abc(j)) |
answer: Heyy buddy, I did not understand the question. can u plz send me your code at laukik1903@gmail.com so that I can understand what u r trying to say. It wud b a gr8 help. Thank you in advance. |
answer: I was confused by this question.Say input three lines likeaaabcaThe order should be "acb" or "abc"? |
answer: in your example, there is not enough information to determine the relationship of "c" with respect to "b". And in this case it is impossible to build a sorted alphabet based only on these three strings. All what we know is that a<b and a<c. |
answer: In Kido’s example:aaabcaThe order would be c a b, as c < a < b.. |
question :
Asked to extract numbers from a list of alphanumeric strings. For example if string is "qw34rt56", new list should contain 34 and 56. New list should have unique numbers and should be in ascending order. They requested write complete code and tell over the phone. |
answer: I have used TreeSet data structure from Java to accomplish the task. |
answer: 1. User regular expression to get the different numbers from the string, something like ([0-9]+)[^0-9]2. Add the numbers to a main array3. Sort the array.4. Remove duplicate entries. |
question :
What are the first 2 integers that, when added together, equal 10 in a "very large" array of unsigned integers? |
answer: My in-interview answer was bad!!! I came up with a better one using a 2d array with 11 rows and 2 columns. First column to hold the first occurrence of each integer 0-10 (conveniently, the indices of each row match a relevent integer) and second column to hold the second occurrence of 5. When you first encounter an integer that can be used to equal 10, add the index to the first column. When encounter 5 for the second time, add it to the second column. Each time you update a value, check to see if both sides of the equation are populated…if so, you have your answer, if not continue on with the original array. Note: Adding the index enables you to keep track of WHERE the integers were in the original array, however if that doesn’t matter, you could update it with any value that works for your evaluation logic. |
answer: It’s a specific case of the problem of finding two integers that add up to a given number in a list of integers. In general case, you do need to sort first and use two pointers from start and end and use an elimination to search in O(n).In this case, since sum is already given (a constant) we just need to maintain last unique indices of integrers <= 10. Any time we find two that adds up to 10 is the answer. |
answer: if it is a "very large" collection, avoid sorting; i think we are creating a time consuming cycle there. i have given a little piece of code for a similar question in this forum itself, which can be used as a starting point for bettering your answers. i got this question few years ago, when i went for an interview, with a bay area network security company.. as a UI developer !! |
answer: should not sort it. Create an array or length 11 (index of 0-10), call it H, fill it with null (you can use -1 as null)Call original array A. Code is very simple:i = 0while(i++) complement = 10 – A[i] if(H[complement] == null) H[complement] = i else breakat this point A[H[complement]] + A[i] == 10I’m essentially using H as a hash table where hash(n) = nthis solves the problem in O(n) I believe. |
answer: I think hashing is preferred in this case. |
answer: @maxzed2kI’m not entirely sure if your solution will cover all cases. What if the complement (i.e. 10-A[i]) is negative?H[ <a negative number> ] will give you a segmentation fault. |
question :
Tell me about your skills with Excel. |
answer: My jaw dropped. Seriously, this is the first question you have for a marketing director?? |
answer: I’m currently in the interview process at Amazon for a different though related position. During my second telephone interview, I was asked a task-oriented question related to Excel functionality. I was also asked to describe basic HTML functionality. The questions struck me as odd, but I guess they’re exploring a candidate’s basic skill set. This leads me to wonder if they typically run into folks who claim to know more or have more experience than they actually do. It was…interesting. |
question :
Find the first non-repeating character in a string |
answer: The straightforward answer is to loop over the string, and for each character check the whole string if it is repeated.This solution is O(n^2).Better would be to remember each character visited and keep a count of how often it was encountered. You would initially have a 0 count for every character in the alphabet, or an empty hash map with the same purpose. Then go over the whole string and increment the counter for each character you encounter.Finally, go over the string and look up for each character how often it was encountered. The first one with a count of 1 is the one you are looking for.This algorithm requires the list to be searched twice, and is O(n). |
answer: In Java, better than O(n), ie returns in < 256 checks. Small RAM footprint since it uses one Byte (the BitSet instance) to track characters.public char check(String text) { BitSet set = new BitSet(256); for (char ch : text.toCharArray()) { if (!set.get((int)ch)) { set.set((int)ch); } else { return ch; } } return 0; } |
answer: This function is wrong:In Java, better than O(n), ie returns in < 256 checks. Small RAM footprint since it uses one Byte (the BitSet instance) to track characters.public char check(String text) { BitSet set = new BitSet(256); for (char ch : text.toCharArray()) { if (!set.get((int)ch)) { set.set((int)ch); } else { return ch; } } return 0; }It returns the first REPEATING character, not non-repeating character like the OP asked. |
answer: This following code should work for finding first unrepeatable char in stringpublic static char checkFirstUnRepeatableChar(String text){ BitSet set = new BitSet(256); BitSet repeated = new BitSet(256); for (char ch : text.toCharArray()) { if (!set.get((int) ch)) { set.set((int) ch); } else { repeated.set((int) ch); } } for(char ch : text.toCharArray()){ if( !repeated.get((int)ch)) return ch; } return 0; } |
answer: According to me, one can better create a hash table with each alphabet as a key of the string and then use chaining for recurrence of the alphabets…. Now simply apply searching algo to find first alphabet with zero repetition… |
question :
Sort the first 100 numbers from a incoming input stream of milions of numbers. |
answer: Can do this by using either a self balancing binary tree or a min heap. Basically construct a heap/tree from the first 100 numbers from the tree. There after read one number at a time from the stream and compare with the smallest in the heap/tree, if the incoming number is larger then delete the smallest number and add the incoming number to the heap/tree. Heapify/rebalance the tree and repeat operation. O(n log (n)) |
answer: @answerYou mean a max heap of the smallest 100 numbers, right? This will help identifying the largest number and easily replacing with something smaller. |
question :
Determine the first non-repeated character in a word. For example, in abbcaf it should return c. Do this in O(n) time with O(1) space. |
answer: public char findFirstSolo(String input){ List[] buckets = new List[ alphabet.size ]; for(char c in input){ List curr = buckets[c]; // get appropriate bucket curr.add(c.index); // add index to list } int earliestIndex = infinity; for(List bucket in buckets){ if(bucket.size == 1){ if(bucket[0].index < earliestIndex){ earliestIndex = bucket[0].index; } } } return input.charAt(earliestIndex);} |
answer: does O(1) mean, I can use a fixed 256 size array? |
answer: public static char findFirstSolo(String input){ int[] letters = new int[26]; int pos = 0; for(char c : input.toCharArray()){ ++pos; if (letters[c – ‘a’] == 0) letters[c – ‘a’] = pos; else letters[c – ‘a’] = Integer.MAX_VALUE; } char firstSolo = (char)0; int earliestIndex = Integer.MAX_VALUE; for (int i = 0; i < 26; ++i) { if (letters[i] < earliestIndex && letters[i] != 0) { earliestIndex = letters[i]; firstSolo = (char) (‘a’ + i); } } return firstSolo; } |
answer: Since the alphabet is not dependent on n, it is O(1)char firstNonRepeated(String input) { int letters = new int[26]; for(char c : input.toCharArray()) letters[c-‘a’] ++; // assuming initialized to 0 for(char c : input.toCharArray()) if (letters[c-‘a’] < 2) return c;} |
question :
design the objects needed to run a jukebox. |
answer: I designed a system with three major parts, the UI, the record/disc manager, and a control object |
answer: Disc, Player, MoneyManager, Player, UI (of course and all its necessities) |
question :
Given a time-ordered log of user visits to web pages find the most common 3-page sequence |
answer: Originally just presented as "a log of user web page accesses" I pressed him for the "time-ordered" part and made sure each transaction was marked with a user-specific ID. My solution was to split of the list by user, then assign three iterators to the first three values. Then use a three-tiered hashmap indexed by the first, second, then third page to store a sequence count. Each iteration we’d increment the value stored at map[pg1][pg2][pg3]. |
answer: I think you have to use dynamic programming that is HMM for this..viterbi algorithm suits best for this.You can also answer many queries using that algorithm. |
question :
Find the deepest common ancestor of two nodes in a tree structure. |
answer: This interview was frustrating because it felt like the woman couldn’t write code in C++. I first asked whether I could assume a standard Tree node structure (as I’ve built several custom structures and they all have many of the same basic components) and she was pretty much dumbstruck and told me ti write the implementation for one. So i did. Then I started walking through my solution and practically had to spell the word iterator when I said I declared one. My solution was basically to just descend in the tree toward the first value until the two values are on different sides of the current node or you fall out the bottom of the tree. I had to repeat the conditional statements character by character for the interviewer. |
answer: Isn’t the root node always the "deepest" common ancestor? Either the question is worded wrong, or you answered it incorrectly, but I think it’s most likely that it’s worded wrong. |
answer: @mliuthe question is correct. u r thinking wrong.depth of a tree grows towards its leaves.root is the least deep node in a tree. |
answer: @nunnu is right here what the question wanted was the common ancestor furthest from the root. Again, I’m pretty sure (by subsequent conversations with friends) that my answer was right but that the interviewer and I just couldn’t communicate |
answer: struct node{ int value; struct node *right; struct node *left;}mynode;mynode *closestAncestor(mynode* root, mynode* p, mynode* q){ mynode *l, *r, *tmp; if(root == NULL) { return(NULL); } if(root->left==p || root->right==p || root->left==q || root->right==q) { return(root); } else { l = closestAncestor(root->left, p, q); r = closestAncestor(root->right, p, q); if(l!=NULL && r!=NULL) { return(root); } else { tmp = (l!=NULL) ? l : r; return(tmp); } }} |
answer: Smiles, my ancestors don’t sit in trees. – Do yours?We have grown used to sitting under them and have great picnics… |
answer: Suppose we need to find common ancestor for the nodes with values A an B.start from the root and compare value of the root node with both A and B. If A an B are both below/above the node’s value then go down to the next node. Repeat until we find a node where A and B "go" to different links. This node seems to be ‘common ancestor’. |
answer: Traverse up the tree for both the nodes and add them to the explored list. If there is a common element in the explored list of both the nodes, that’s the common ancestor. |
answer: Hari, if the answer was the root your approach would have n^2*lg(n) complexity where mine had lg(n) in the worst case |
answer: solution with O(h) time and memory complexity (h – height of the tree)Node * dca(const Node * a, const Node * b) { stack<Node *> qa, qb; while (a) { qa.push(a); a = a->p; } while (b) { qb.push(b); b = b->p; } Node * result = NULL; while (qa.top() == qb.top()) { result = qa.top(); qa.pop(); qb.pop(); } return result;} |
answer: To find the common ancestor. O(lg N) public Node GetCommonParent(Node root, int key1, int key2) { while (root != null) { int key = root.iData; if (key < key1 && key < key2) root = root.RightChild; else if (key > key1 && key > key2) root = root.LeftChild; else return root; } return null; } |
answer: @Joarder: your answer is both really bad coding practice and only works for very specifically-structured trees (binary search trees based in integer keys). The approach is a good one, but you should not override a parameter being passed in and you should use Node.isLeft(Node) and Node.isRight(Node) rather than comparing keys directly. Remember that a tree can be made from a collection of any comparable object, keys are not required. |
question :
Layout the fundamental objects to build a restaurant reservation system. |
answer: I’m not going to go into the interaction here but the basics of what she wanted were the objects: Table and Guest, the metadata that would be stored in each and the basic subsystems to manage them. She also had me lay out the basic processes involved including reserving a table. There was a disagreement as to whether the system assigns guests to tables or the service staff; while in every version of this system I’ve ever seen the system just knows capacities and sitting times she wanted the system to manage the whole restaurant. |
answer: http://devinterviewgyan.blogspot.com/2010/03/design-restaurant-reservation-system.html |
question :
Reverse a linked list. |
answer:
This post has been removed. Please see our |
answer: you can reverse the data field in the linked list if you are asked not to use extra pointers… |
question :
You have 25 laborers for a shift. Pickers pick 100 units an hour Small item packers pack 150 units an hour Large item packers pack 25 units an hour You must pack 7500 small units during a ten hour shift. How would you staff your shift? |
answer: 10 Pickers 10,000 units/shift5 Small Item Packers 7500 units/shift10 Large Item Packers 2500 units/shiftThis was the right answer, they have you explain it. |
answer: I must be thick because I don’t understand your answer. You picked 3 options. What is the correct answer? |
answer: Ron, the goal is to balance out the shift while meeting the one demand (7500 small items packed). so you know you will need 5 small item packers. what to do with the other 20? The answer is correct. I just happen to have an area manager interview in Phoenix this thursday and now I know the question and answer |
answer: You gave a single answer…Right answer? sure.Right response? no.25 Workers (breaks up nicely with 5 laborer unit ratios):A) 3:2 Pickers to Small Item PackersB) 1:4 Pickers to Large Item PackersC) 2:1:2 Pickers to Small item Packers to Pickers5 Small item packers are required.Any combination of A, B and C where the number of small item packers >= 5.Candidate’s response: 5*C (A valid answer only meeting the minimum demand for small items)Why would the candidate’s answer be better than 5*A?15 Pickers 15,000 units/shift10 Small item Packers 15,000 units/shiftWhy would the candidate’s answer be better than 2*A + 3*C?12 Pickers 12,000 units/shift7 Small item Packers 10,500 units/shift6 Large item Packers 1,500 units/shiftWhy would the candidate’s answer be better than 3*A + 2*B?11 Pickers 11,000 units/shift6 Small item Packers 9,000 units/shift8 Large item Packers 2,000 units/shift^–If they asked for a single solution, I’d argue this one would be better since you buffered the small item output. |
answer: Why wouldn’t you use the following variation as it maximizes the potential for daily output4*A +1*Bresult would be13 Pickers 13,000 Units/shift8 Small Item Packers 12,000 Units/Shift4 Large Item Packers 1,000 Units/ShiftJust a question…. |
answer: Maximizing your daily output is not necessarily the way to go. You have customers waiting for orders and if you work on mostly smalls, the amount of large units in your backlog will be high. So while your numbers look good, you may not being getting orders out to customers timley. This question would make more sense if it said how many units have been ordered of small and large items so you can be sure to get through the orders in a FIFO basis. |
question :
How to detect loops in a linked list without using a data structure |
answer: start a fast pointer and a slow pointer each traversing the list. if they ever point to the same place after the start, then they are both caught in the same loop. |
answer: Check out the Wiley’s book "programming interviews exposed" that discusses this question in detail. Coming up with jeremy’s solution on the spot is close to impossible.You could check for every position i you come by as you jump from node to node, if any of the previous i-2 nodes’ next pointer points to you. If there is a cycle, one will point to you. |
answer: fastest way:suppose there is ‘value’ field in each node of linked list other that ther ‘next node pointer’as you traverse the list .. make the value field -1 or something like MAX_INT…. keep doing it either list ends or you see MAX_INT again… |
answer: Jeremy’s answer is right; it’s called Floyd’s cycle finding algorithm |
question :
How do you implement a HashMap in java if suppose there was no java.util.HashMap class available. |
answer: write a class which can have two array list.one to store key and another to store value. use some indexing algorithm, to make good performance. |
answer: Instead of using 2 lists; which could make synchronizing (when adding/removing) these lists an overhead you could use a 2 dimensional array. |
answer: @NoRiddim, Can you elaborate the two dimensional approach? How do you store the row_index & column_index values? |
question :
Number of 1’s in binary representation of integer? |
answer: Run a loop, in which you binary-AND the integer with 1, and increment a counter, if the result is 1. Then right-shift the input-integer by 1 bit, and start over in the loop |
answer: unsigned int ones(unsigned int number){ unsigned int n; for (n = 0; number != 0; number >> 1) { if (number & 1) { n++; } } return n;} |
answer: unsigned int ones(unsigned int number){ unsigned int n; for (n = 0; number != 0; number >> 1) { if (number & 1) { n++; } } return n;} |
answer: i dnt knw wheather it correct or not…..do correct me if im wrnga=0q=n/2r=n%2n=qif(r=1)thena=a++continue…. |
answer: ct = 0;while (val) { ct++; val = val & (val – 1);} |
answer: Several of the above work, but use preincrement |
answer: public static int population(int x) { x = (x & 0x55555555) + ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x & 0x0F0F0F0F) + ((x >> 4) & 0x0F0F0F0F); x = (x & 0x00FF00FF) + ((x >> 8) & 0x00FF00FF); x = (x & 0x0000FFFF) + ((x >>16) & 0x0000FFFF); return x;} |
answer: in C++, how about:do { sum += n&1; } while (n>>=1); |
answer: int ones( ) { int n; int number = 1100110111; n = 0; while (number!=0) { int temp = number % 10; if(temp ==1 ) n++; number = number/10; } return n; } |
answer: Lets consider 14(1110) is the numberint CountOnes(int Number){int n=0;while(number !=0){if(number%2==1) n++;number >> 1;}return n;} |
question :
How would you implement integer division if your language did not offer it. |
answer:
http://www.bearcave.com/software/divide.htm |
answer:
#Assumes positive numbersdef divide(num, divide_by) answer = 0 return answer if divide_by == 0 while(num >= divide_by) num = num – divide_by answer = answer + 1 end answerendputs divide(10,0) |
answer: I think this is all you need, as the question asks for integer divisionI.e. 2 integer inputs to provide integer output3 / 4 = 0 (dividend is less than the divisor)2 / 1 = 2 (divisor is 1)4 / 2 = 2 (divisor is a factor)7 / 5 = 1 (dividend is greater than divisor)Note: solution below is for positive integerspublic static double divide(int dividend, int divisor) { int remainder = dividend; int count = 0; while (remainder > divisor) { remainder -= divisor; count++; } return count; } |
answer: EDIT:To also handle divide by zero and negative numberspublic static int divide(int dividend, int divisor) throws ArithmeticException{ int remainder = dividend; int count = 0; if (divisor == 0) { throw new ArithmeticException("Divide by 0"); } if (remainder > 0 && divisor < 0) { divisor *= -1; while (remainder >= divisor) { remainder -= divisor; count–; } } else if (remainder < 0 && divisor > 0) { remainder *= -1; while (remainder >= divisor) { remainder -= divisor; count–; } } else if (remainder < 0 && divisor < 0) { remainder *= -1; divisor *= -1; while (remainder >= divisor) { remainder -= divisor; count++; } } else { while (remainder >= divisor) { remainder -= divisor; count++; } } return count; } |
question :
Given an array of integers, all but one of which appears an even number of times, find the one integer which appears an odd number of times. Upon completion, asked to improve the algorithm in terms of both time and space, eventually asked to do it in O(n) time and constant space. |
answer: xor the entire array, all the integers which appear an even number of times will cancel eachother out |
answer: int[] theArray = new int[]{1, 1, 2, 2, 3, 3, 3, 4, 4, 10, 10, 10, 10, 10, 11, 11, 12, 12}; Map<Integer, Integer> theMap = new HashMap<Integer, Integer>(); for (int i = 0; i < theArray.length; i++) { if(theMap.containsKey(theArray[i])) { theMap.put(theArray[i], theMap.get(theArray[i]) + 1); } else { theMap.put(theArray[i], 1); } } Set<Integer> mapKeys = theMap.keySet(); for(int keyInt : mapKeys) { if(theMap.get(keyInt) % 2 != 0) { System.out.println(keyInt + " occurs odd number of times"); } } } |
answer: I was also asked this in 2010,march. |
answer: XOR |
question :
How would you reverse a linked list in Java? |
answer: List.reverse() |
answer: java.util.Collections.reverse(yourList); |
answer: First answer is incorrect (no such method). 2nd answer is correct. I’ve seen this question before where the expected answer is to manipulate the list. |
answer: public class LinkedListElement<E> { private E _element; private LinkedListElement<E> _next; public LinkedListElement(E element) { _element = element; _next = null; } public LinkedListElement(E element, LinkedListElement<E> next) { _element = element; _next = next; } public E get() { return _element; } public LinkedListElement<E> next() { return _next; } public void setNext(LinkedListElement<E> next) { _next = next; } public static <E> LinkedListElement<E> reverse(LinkedListElement<E> e) { if (e == null) { return null; } LinkedListElement<E> current = e; LinkedListElement<E> next = e.next(); e.setNext(null); while (next != null) { LinkedListElement<E> forward = next.next(); next.setNext(e); e = next; next = forward; } return e; }} |
question :
You are to write a spell checker. Discuss the API, Data Structures and Algorithms. |
answer: Did not know the answer but worked through the answer interactively with the interviewer. This was during a phone interview. Did not get the full solution, but still got accepted for the site visit. |
answer: two parallel approaches are needed:sounds like (mapping)single typo (search by character) |
question :
If you saw someone steal a quarter. Would you report it? |
answer: yes |
answer: No. I’d talk them out of it. Pay them a quarter from my own pocket if I had to. Who’s integrity is worth 25¢? |
answer: Easy to steal quarters? Where can I get in on this action? |
answer: It is all part of a yes/no integrity test. The answer is "YES" because they want to know that you think ANY theft is wrong. |
answer: It depends, if I saw a customer at Walmart reach into the til when the cashier is not looking, I would turn the person in. If my best friend stole a quarter from me, I would not turn her in. |
answer: What is this?……the plot of Office Space where the guys use a computer program to steal pennies off of each transaction the company makes and then end up getting really rich??? I say if it’s just one quarter, it’s not worth it. Most stores don’t prosecute for petty theft of even $50 or $100. It’s not worth your energy. |
answer: Coming from retail management and knowing how LP is looking at this:It starts with a quarter and usually gets bigger from there. (Greed )I believe the only right answer is YES its stealingIf you are willing to may exception because of the amount it shows that you will bend rules and fail the question.I have worked before companies that fired people for consuming discarded merchandise(written out of inventory like an open package of such-and-such) because it was a policy. Most comanies want to know their policies will be followed to the letter because that helps product the company.Although some companies may bend their rules where they see fit that is not what the interview is about . |
answer: steal a little steal big, there’s only one word to it. thief. |
answer: steal a little steal big, there’s only one word to it. thief. I will report it. |
answer: Short answer – Yes/No.Deal with it YES. Report it, depends on the circumstances and outcome of my attempt to deal with it.Consider:If I saw someone pocket a quarter from the cash register or steal a small product ($.25 worth) I would definitely report it, but I’d give them the chance to report themselves first. Kind of like my parents would handle it with me, and how I handle it with my children – you steal, you return the merchandise AND pay for it AND apologize. If that doesn’t settle the matter we proceed from there.Compared to …If I saw someone pocket a quarter left on the lunch table at work after a few people got up I would not ‘report’ that, but would certainly handle it the same as above i.e., make sure they gave the $ (any amount) to one of the people who was sitting there.In Florida this is embraced by a grocery chain called Publix. They call it the Publix Price Guarantee – if they accidentally error on your checkout and you point it out to them they give you a refund for the item AND the item (free).Sorry for the long-winded response, but some of these ‘behavioral’ questions simply taunt us to relinquish personal &/or social responsibility in the name of ‘proper procedure’. If we don’t take responsibility for seemingly ‘little things’ we are in no position to ‘blame’ anyone when big things go wrong.Kind of like if something bad was happening in the workplace. If I feel it’s unsafe to the point I need to leave I will certainly let my manager (and certain other people) know before departing. I think this perspective was forged by a combination of personality and experience. I had the opportunity to visit the WTC on 2/26/1993 for my company after the bombing, so all my co-workers and friends know there comes a time when YOU MUST DECIDE if you stay or if you leave. Restating the point, there comes a time when YOU MUST DECIDE to speak up &/or take action about improper (or illegal) behavior – at the workplace or anywhere else.Happy Holidays all. |
question :
I got questions like "Given a dictionary of words, how do you calculate the anagrams for a new word". |
answer: One answer was to precalculate a 26 element array for each dictionary word where an array element represented how many occurences of the corresponding letter of the alphabet occured in that word. |
answer: You wouldn’t. A new word would not appear in the dictionary. |
answer: One way to do this would be to take each word in a dictionary and sort it and store it as a key in a hash. the values will be all the words that map to this one, stored as a list. |
answer: Store all anagrams for the new word in a 2-dimensional array (column 1 = anagram, column 2 = flag). Compare each element in column 1 with words in the dictionary until found. If found, flag = good anagram, else flag = bad anagram!Just a guess. Suggestions please. |
question :
How would you implement a top 3 word count in a text editor application? |
answer: What is the answer to this question? Would one just parse through the whole document and hash each word occurrence, with the key as the word itself, and the value as the number of occurrence? |
answer: Can we use a BST to store word and length values? And then do a pre-order traversal? |
answer: Another approach would be to sort in place in n log n. Then scan the sorted list of words and maintain a count of top three. |
answer: max-Heap |
answer: This can be done using Linked Hash.Each element of Hash has two pointer. Min pointing to element which comes next in the seq with <= count.Max which points to element which has > count.When we add new word, either it will be added to hash or updated its count. If count is updated then we need to correct the Min and Max pointer accordingly. Also we need to corecct obj.Min.Max pointer and obj.Max.Min pointer accordingly.Keep track of the Max and Min element of the heap elements.Other optimization can be done to improve the worst case scenario like storing head pointer of list of words which has same count. |
answer: Using Heap and Hash will solve the problem optimally.Keep a hash of word as key and count as value. And keep a Min heap of 3 elements.Build the heap with first 3 elements.For every new element increase the count in HashMap.Check if the element is in the heap, then update the count and reheapify.Else check if the element count is greater than top element of Min heap, if yes then replace that element with our new element and reheapify.Else don”t touch our heap and keep counting.This will make sure the heap will always have top 3 elements.Complexity: O(n) as heapify is constant always. |
question :
Determine whether the binary representation of a number if a palindrome or not, code it on a white board. |
answer: This was the first question I was asked and is considered a warm up. |
answer: public static boolean isPalindrome(int someInt) { final int WIDTH = 8; boolean isPalindrome = true; for (int i = 0; i < WIDTH && isPalindrome == true; i++) { int maskLower = (int) Math.pow(2, i); int maskUpper = (int) Math.pow(2, WIDTH – (i+1)); boolean bitLowerOn = ((maskLower & someInt) == maskLower) ? true : false; boolean bitUpperOn = ((maskUpper & someInt) == maskUpper) ? true : false; isPalindrome = bitLowerOn && bitUpperOn && isPalindrome || !bitLowerOn && !bitUpperOn; } return isPalindrome; } |
answer: anon.. would this work for a number like 17 (10001)? |
answer: bool checkPalindrome(unsigned int n){ int m = n, k =0; bool ret = false; while(m!=0) { int i = 1; i = i & m; k = k << 1; k = k | i; m = m >> 1; } if((k^n)==0) { cout<<"Palindrome"<<endl; ret = true; } else { cout<<"Not Palindrome"<<endl; } return ret;} |
answer: I have a simple solution. Reverse the bits one by one and test equality of the two resulting numbers. (Matlab code)function [r] = isPalindrome(a)n = a;m = 0;while(n>0) m = bitshift(m, 1); m = m + mod(n, 2); n = bitshift(n, -1);endr = (m==a);end |
answer: public static boolean isPalindrome(int n) { int nb = 0, nl=n; while(nl>0) { nb=(nb<<1) + (nl&1); nl=nl>>1; } return nb==n; } |
answer: @john/catalin4ever,i think it’ll fail because it doesn’t concat the 0s. For example: if the input is 0110,then after execution "nb" becomes to 0011. this is because of the condition: while(nl>0) |
question :
Implement a simple load balancing algorithm in pseudo code (over the phone) |
answer: Not easy. You’ll have to explain and code it… ON THE PHONE. |
answer: min heap for the load factor. periodically you construct that heap and the other requests pick the root of the heap |
question :
Sorting a list of some random type |
answer: Don’t use brute force. At the very least offer some comments that shows you are thinking of more efficient solutions. |
answer: Insert the items into a TreeSet (assumes the elements are comparable). Iterate through the loaded set. |
question :
Design an email sender that can send 100,000,000 emails. You have 5 machines how could you do it efficiently. |
answer: Need to discuss where the performance bottlenecks are and how to mitigate them. |
answer: You could probably have your input application send messages to a clustered queue. There are 5 servers running on the 5 machines, each server with its own MDB. The MDB would then pick it up from the JMS queue and send it to the recipient. The queue depth of the intermediate queue should be sufficient enough to allow sufficient buffer so that you dont have to worry about your input program putting messages at a much faster rate than the MDBs can process. |
answer: use worker threads aka. Executors they have internal job queues that worker threads pick on. Provides high parallelism |
question :
Given a string find the first non-repeated character. |
answer: Hint: use a hash table |
answer: public static char getFirstNonRepeatedChar(String s) { List<Character> charList = null; char nonRepeatedChar =’?'; if (s != null) { s = s.trim(); charList = new ArrayList<Character>(); for (int i=0; i<s.length(); i++) { Character c = s.charAt(i); if (!charList.contains(c)) { charList.add(c); } else { charList.remove(c); } } } if (charList != null && !charList.isEmpty()) { nonRepeatedChar = charList.get(0); } return nonRepeatedChar; } |
answer: @Rajiv : Your solution is completely wrong. It will fail for input of "aaa"Reason: on first check, you insert "a". On next check you remove it. On next check you again insert it and return that as your answer, even though it was repeated thrice. |
answer: hash of non repeating characters tied to a double linked list, remove any repeating character from the hash and the list. at the end the head of the list is the answer. you can use the same hash to keep the counters. |
answer: public static String findFirstNonRepeatedCharacter(String S) { int[] T = new int[256]; for (int i = 0; i < S.length(); i++) { char next = S.charAt(i); T[next] = T[next] + 1; } for (int i = 0; i < S.length(); i++) { if(T[S.charAt(i)] == 1) return String.valueOf(S.charAt(i)); } return null; } |
question :
Binary tree with parent pointers, given two nodes find common ancestor. |
answer: Hint: use a hash table |
answer: For each node traversed from the root,if both values are less than the current Node, then move to the leftif both values are greater than the currentNode, then move to the right,if the value of current Node is between value 1 and value 2, then you have found the nearest common ancestor. |
answer: Rajiv, you can’t do that is tree is by parent pointers. you need to bubble up from the given nodes and put parents to a hash. |
question :
Given two linked lists A and B, return a new linked list C, where C consists of all elements in A or B that are contained in only A or only B. |
answer: Hint: hash table! |
answer: public static void createUniqueListC(List<Integer> listA, List<Integer> listB) { Set<Integer> set = null; List<Integer> list = null; if (listA != null && listB != null) { set = new LinkedHashSet<Integer>(); list = listA; int length = listA.size() + listB.size(); for (int i=0; i<length; i++) { if (i>=listA.size()) { list = listB; i = 0; length = length – listA.size(); } if (!set.add(list.get(i))) { set.remove(list.get(i)); } } Iterator<Integer> itr = set.iterator(); while (itr.hasNext()) { System.out.println(itr.next()+" "); } } } |
question :
Print out all the permutations of a string. |
answer: this was my last interview, was tired, and didn’t make progress till I ran out of time. Definitely should have ran through a couple practice problems before the interview. |
answer: My favorite approach is to use a bitvector. As the best-case complexity is O(n*2^n), it not feasible to permute a large N. An integer (32-bits) or long (64-bits) is good enough. Each bit acts as a flag of whether the character can be shown. Increment and show until the end-point is reached.For example, "abc" has the permutation of:000 –> ___001 –> __c010 –> _b_011 –> _bc100 –> a__101 –> a_c110 –> ab_111 –> abcThe code is very simple and lazily evaluated, so it has O(1) space complexity. A gray code counter could be used to have a cleaner output, but that’s a nit. |
answer: The answer given by Ben is wrong, as it is not printing a permutation of the string.For example, given abc, the permutation of abc will result inabcacbbcabaccabcbaThe complexity of the algorithm described below is (n!) as the permutation of any string will result in printing the string n! times.First of all, an example to illustrate the algorithm.Given "abc",select the first character in this case "a"permute the remainder, "bc" of the stringwith the new list, push a into all possible positionspseoducode:function ArrayList<String> permute(String s) { ArrayList<string> permutations if string is null, return null, if string length is equal to zero, add an empty string into the permutations array list a = first character in string remainder = string.substring(1); ArrayList<String> permutedRemainder = permute(remainder); //here’s where the n! complexity comes in for every value in permutedRemainder { for(int position = 0; position < string.length; position++) { permutations.add(merge(string, first letter, position); } } return the ArrayList permutations}the only thing left is to write a merge function which will insert the given character into the given position in the string. |
question :
Write a program to count the number of words in a file. |
answer: You have to code a program over the phone. |
answer: What I would look for in an answer here would be for the person to focus on the definition of what delimits a word. Then a state machine construct that counts the number of transitions from the "in a word" state to the "out of word" state would be the word count * 2. |
answer: #!/usr/bin/perl -wmy $cnt = 0;while(<>) { my $num_blanks = s/ +/ /g; $cnt += $num_blanks + 1;}print "$cnt\n"; |
answer: wc -l <filename>Not a program per se, but works |
question :
Describe what do you write in a functional specification? |
answer: It really depends on the type of product you’re developing..and each company has a different approach on what’s important in the doc. So unless you know what is important to Amazon, answering this question can be tough. |
answer: A functional spec should say what the product should do and describe inputs and outputs. The internal workings of how the product should work are ignored. Basically the functionality from a user perspective needs to be described and implementation details avoided. |
question :
Find the first character in a stream which is not repeated in the rest of the stream. Please note that you are being provided a stream as a source for these characters. The stream is guaranteed to eventually terminate (i.e. return false from a call to the hasNext() method), though it could be very long. You will access this stream through the provided interface methods. A call to hasNext() will return whether the stream contains any more characters to process. A call to getNext() will return the next character to be processed in the stream. It is not possible to restart the stream. Example: Input: aAbBABac Output: b In this example, the character ‘b’ is the first character in the stream which is not repeated in the stream. |
answer: Create a dictionary and count the numbers |
answer: Since you need to know the FIRST non-repeated character, you need an ordered data structure. I’d use a linked list to do this. We also need to know if we’ve seen a character before, so you need to keep track of seen characters and their occurances (since we only need to know if it occurs more than once, you could so HashTable<char, bool> instead of <char, int>.The algorithm would be:– get next character– if we’ve seen it before and more than one time, skip to next character– if we’ve seen it before, but only once, then remove it from the list of possible solutions and set its hashtable entry to seen more than once– if we’ve never seen it, store it in the hashtable as seen only once and add it to the end of the possible solution lists– loop while there are more characters in the stream– when we run out of characters, the head of the possible solution list will now contain the first non-repeated character |
question :
Aptitude question ( may be i was not ready for it) |
answer: I have been recently interviewed by Amazon for the same role. The First round was Test cases enumeration round, My interview lasted for about 50 Mins. Can you please tell me how did they communicate your interview feedback. I am waiting for a response from them yet(my interview happened yesterday). |
answer: Hi,All the best for your interview result if u have not informed yet. I waited for a day and the next day i sent email to the HR person and immediately got the reply about the result.Thanks |
question :
Given 2 eggs and there are 100 steps. Need to find the step from which the egg starts breaking. What is the minumum tries? |
answer: n(n-1)/2 = 100 |
answer: Imagine we drop our first egg from floor n, if it breaks, we can step through the previous (n-1) floors one-by-one.If it doesn’t break, rather than jumping up another n floors, instead we should step up just (n-1) floors (because we have one less drop available if we have to switch to one-by-one floors), so the next floor we should try is floor n + (n-1)Similarly, if this drop does not break, we next need to jump up to floor n + (n-1) + (n-2), then floor n + (n-1) + (n-2) + (n-3) …We keep reducing the step by one each time we jump up, until that step-up is just one floor, and get the following equation for a 100 floor building:n + (n-1) + (n-2) + (n-3) + (n-4) + … + 1 >= 100This summation, as many will recognize, is the formula for triangular numbers (which kind of makes sense, since we’re reducing the step by one each drop we make) and can be simplified to:n (n+1) / 2 >= 100This is a quadratic equation, with the positive root of 13.651 ~ 14 attempts |
question :
How can you find the biggest the number in 2 arrays, and they are not sorted. What is the time complex. implement it and send it to someone. |
answer: sort them, and using 2 pointers from one side(biggest side) at the same time, start to compare, if not the same, bigger move to next , if same break. nlog(n) |
answer: Why would you need to sort them? Just iterate through and find the largest number? O(n) |
question :
Suppose that 10% of the products sold online were incorrectly priced. What could be a possible solution to this problem and detail out the approach you’ll follow. |
answer: It depends upon the situation,in both the cases what could we do is if cost of the product were priced higher than what expected than we can simply requested to the customer that next perches item by them will be adjusted accordingly and visa versa if cost is less… |
answer: I guessed that they were looking for a preventive approach as a solution. So I told them that there are two things that can be done. One is to perform an external benchmarking with the direct competitor on similar product portfolios. This will involve a detailed analysis on how they are able to sell the same product at a better price value. A possible hypothesis is that the competitor has a larger pricing band owing to the number of suppliers in his kitty.Second thing is to attract customers by giving out offers and discounts. I atleast thought this answer went well them |
question :
Only from glass door and career cup |
answer: * Given two trees how will u find if one is a mirror image of the oher*/function areTheyMirror(root1, root2){ if(root1.value != root2.value) return false; else if( root1.value == null && root2.value == null) { /* * we hit the leaves */ return true; } else { if (areTheyMirror(root1.left, root2.right) && areTheyMirror(root1.right, root2.left)) { return true; } }} |
answer: /**Hexadecimal to decimal*/private static final String hexCode[] = {"0", "1", "2", "3", "4", "5", "6", "8", "9", "A", "B", "C", "D", "E", "F"};function hexToDec(string input){ int hexValue; int total = 0; for(int i=(input.length-1); i>=0; i–) { hexValue = hexCode.indexAt(input.charAt(i)); total += hexValue * math.power(16, (input.length-i-1)); }} |
question :
In a collection of strings, output the string that occurs most often. |
answer: I honestly had no idea how to solve this in a reasonable amount of time. |
answer: HashMap<String,Integer> map = new HashMap<String,Integer>();for(String str : strings) { Integer count = map.get(str) map.put(str, count != null ? count + 1: new Integer(1) );}// then iterate through map to find the largest integer, the key will be the string with the most occurances |
question :
You are given a fixed number of 5 rupee, 10 rupee, 20 rupee and 50 rupee stamps. Now given an amount for sending a parcel, you should design an algorithm to come out with the minimum number of stamps that should be used for attaining that amount. For example, if the parcel costed 30 rupees, it could be attained using one 20 rupee stamp and one 10 rupee stamp OR using three 10 rupee stamps OR using one 20 rupee stamp and two 5 rupee stamps OR using one 10 rupee stamp and four 5 rupee stamps OR using two 10 rupee stamps and two 5 rupee stamps. However, the minimum number of stamps is the case of one 20 rupee stamp and one 10 rupee stamp where only two stamps are used. The case where no solution is possible should also be handled, for example, a parcel amount of exactly 33 rupees cannot be attained. |
answer: The solution is attained using dynamic programming. The basic idea is that the minimum number of stamps used for attaining an amount x, is 1+minimum of (minimum number of stamps for attaining x-5, minimum number of stamps for attaining x-10, minimum number of stamps for attaining x-20,minimum number of stamps for attaining x-50). You can try to solve this first by assuming that an unlimited number of 5 rupee, 10 rupee, 20 rupee and 50 rupee stamps are available. And then you can take into account that only a fixed number of these stamps are available. |
answer: And what is the time involved to get this done? I really liked the question.Simple to read but involves good amount of logic. I ve written down the algorithm but i believe i took more time than i initially thought i would take. |
answer: I understand what the interviewer is trying to test and I know how to solve it, but what about more realistic scenario where parcel postage cost would be beyond given values like 3 units of currency or 37 units of currency. |
answer: In this specific case, dynamic programming is overkill. There’s a better optimal substructure here: The stamp with greatest value less than parcel cost minus stamp values already committed minimize the total of stamps. |
answer: 1. find the stamp <= cost from highest stamp cost2. num of found_stamp = found_stamp/cost, rem_stamp = found_stamp % cost3. Do 1, then 2 until rem_stamp ==0 (done) or rem_stamp < least stamp available (not possible case) |
answer: In the previous ans, after step 3 if rem_stamp !=0, go back to step 1, find next_stamp < cost (but smaller than value of found_stamp in previous iteration) |
answer: i=0;boolean solPossible = false;do{ if(cost % notes[i] == 0) solPossible = true; else i++;}while(!solPossible && (i<notes.length())if(!solPossible) throw error |
question :
Two sorted arrays. you can start from any one them, and then at common element you may or may not jump to other array. Continue in this manner till you reach the end of an array. Find the path that results the maximum sum. |
answer: Greedy algorithm O(m+n); not really hard once you know it’s greedy. |
answer: DP can also be used…O(m+n) again… |
answer: import java.util.*;class gAlg{public static void main(String[] args){int[] a = new int[5];int[] b = new int[5];int[] c = new int[5];int sum= 0;a[0]=2;a[1]=8;a[2]=9;a[3]=7;a[4]=10;b[0]=3;b[1]=2;b[2]=10;b[3]=9;b[4]=9;System.out.println(Arrays.toString(a));System.out.println(Arrays.toString(b));int i;for(i=0;i<5;i++){c[i]=Math.max(a[i],b[i]);sum = sum+c[i];}System.out.println(Arrays.toString(c));System.out.println(sum);}} |
question :
Given an array of numbers, nums, return an array of numbers products, where products[i] is the product of all nums[j], j != i. Input : [1, 2, 3, 4, 5] Output: [(2*3*4*5), (1*3*4*5), (1*2*4*5), (1*2*3*5), (1*2*3*4)] = [120, 60, 40, 30, 24] You must do this in O(N) without using division. |
answer: Well my answer was to divide the array in 2 different parts perform some logic and in end multiply both the arrays |
answer: One solution would probably be to go through entire array once, keep a track of total product, and then in another loop populate result array by setting each index as totalProduct / (value at index in argument array) |
answer: oh.. but without division. Didn’t see that part with my tiny browser |
answer: If you were not supposed to divide the array into two, for processing….import java.util.*;class aNum2{public static void main(String[] args){int[] a= new int[5];int[] b= new int[5];a[0]=1;a[1]=2;a[2]=3;a[3]=4;a[4]=5;int j;for(j=0;j<5;j++){int i;int p=1;for(i=0; i<5; i++){p=a[i]*p;}b[j]=p/j;}System.out.println(Arrays.toString(b));}} |
answer: if you werent supposed to use the division operator :import java.util.*;class aNum{public static void main(String[] args){int[] a= new int[5];int[] b= new int[5];a[0]=1;a[1]=2;a[2]=3;a[3]=4;a[4]=5;int j;for(j=0;j<5;j++){int i;int p=1;for(i=0; i<j; i++){p=a[i]*p;}for(i=(j+1);i<5;i++){p=a[i]*p;}b[j]=p;}System.out.println(Arrays.toString(b));}} |
answer: Please ignore the very first response .. there is a correction on line 20If you were not supposed to divide the array into two, for processing….import java.util.*;class aNum2{public static void main(String[] args){int[] a= new int[5];int[] b= new int[5];a[0]=1;a[1]=2;a[2]=3;a[3]=4;a[4]=5;int j;for(j=0;j<5;j++){int i;int p=1;for(i=0; i<5; i++){p=a[i]*p;}b[j]=p/a[j];}System.out.println(Arrays.toString(b));}} |
answer: trick is to construct the arrays (in the case for 4 elements) for example { 1, a[0], a[0]*a[1], a[0]*a[1]*a[2], } // productsBelow { a[1]*a[2]*a[3], a[2]*a[3], a[3], 1, } // productsAbove then multiply productsBelow and productsAbovehttp://stackoverflow.com/questions/2680548/interview-q-given-an-array-of-numbers-return-array-of-products-of-all-other-nu |
question :
Lot of questions on the datastructure might be easier to remember all those stuff right out of college but after 9 years of expereince its very difficult |
answer: Please go through the datastrucuture concepts |
answer: Hi… Could you please suggest some questions which was asked in your interview..? |
question :
I did not know what is a red-black tree. And he asked me what collection uses r-b tree. And i just did not know. Didn’t even guess. |
answer: turns out most tree collections in any language is built upon rb tree |
answer: it’s java’s TreeSet |
question :
How would you know how many people are wearing red colour shirt in the city? |
answer: Go to a garments shop . Check for the ratio in which red shirts are available and calculte the red colour shirt percentag multiplied by the urban population .. |
answer: Go to a random corner and get a sample size of about 25 people and note their shirt color. Do it around 10 times to get enough random sampling without bias. Now take this distribution and calculate the population (city) mean and standard deviation. You can guess with 90 to 99% confidence how many people are wearing red shirts. |
question :
Nothing out of the ordinary. Some simple questions on time management, but that is pretty much it |
answer: Like I said, nothing in particular. |
answer: Having QAE interview with amazon this week,Can you let me know the possible qauestions and rounds… |
answer: Having QAE interview with amazon this week,Can you let me know the possible qauestions and rounds… |
answer: Having QAE interview with amazon this week,Can you let me know the possible qauestions and rounds… |
question :
Finding a path in a maze which is represented by a grid of characters. |
answer: Any DFS would do the trick. Don’t forget to label visited nodes! |
answer: One of the two simplest, most straightforward ways:- Depth-First search (http://en.wikipedia.org/wiki/Depth-first_search)- Breadth-First search (http://en.wikipedia.org/wiki/Breadth-first_search)If your maze is very, very long and deep, and has loops and crazies, and is complicated, I suggest the A* algorithm, which is the industry standard pathfinding algorithm which combines a Breadth-First search with heuristics…sort of like an "intelligent breadth-first search".See http://stackoverflow.com/questions/3097556/programming-theory-solve-a-maze?answertab=active#tab-top |
question :
Write a function that divides one number by another, without using the division operator, and make it better than O(n). |
answer: This can be done in a recursive function,the following code is in Python.# get result of a/b without using a "divide" operatordef div(a,b): if a < b: return 0 else: return div(a-b, b)+1This is how human being do the division naturally, however, the running time of this is O(n/m), where n is the size of a, and m is the size of b, which means, O(n/m) is guaranteed to be less than O(n), when m is larger than 1.-Maxim |
answer: The answer above is still O(n). We can use binary search and find the answer in the interval [1,a] and use multiplication operator. |
answer: Totally agree with Vasil. Other option:Long Division Algorithm. O(log n) anyway. |
question :
If you get an array of integers, find the only integer that is repeated for an odd number of times. |
answer: Hint: Hashmaps |
answer: XOR all the numbers |
question :
Yesterday, at 8 am the temperature was -1º (Celsius) and at 8pm it was 22º. What was the temperature at noon? |
answer: No more info so no idea on real answer although I gave a guess at 30º. |
answer: I guess they probably except some people to answer 11° (medium), which is obviously wrong. |
question :
Find the longest subarray which consists of numbers that can be arranged in a continuous sequence. For ex- {4,5,1,5,7,6,8,4,1} output-{5,7,6,8,4}.Find the longest. |
answer: Sort and find longest continuous sub sequence.The time complexity is O(nlog(n) + n) |
answer: ans is no |
answer: @philip, We’ve to find the sub array. NOT sub-sequence. I think its different from LIS problem. |
question :
Given a sorted array. Insert a value into correct position of the array so that the array remains sorted. |
answer: for(i=0;i<MAX_SIZE-1;i++) { /* check for the location, which if found, shift numbers to the right */ if(a[i]>n) { for(j=MAX_SIZE-1;j>=i;j–) a[j] = a[j-1]; break; } } |
answer: Use binary search to find the correct position. O(lgn) comparisons. private static int[] insert(int[] a, int val) { if(val < a[0]){ for(int i = a.length – 1; i > 0; i–){ a[i] = a[i – 1]; } a[0] = val; return a; } else if(val > a[a.length – 2]){ a[a.length – 1] = val; return a; } else return insert(a, val, 0, a.length – 1); } private static int[] insert(int[] a, int val, int start, int end) { int mid = (end – start)/2 + start; if(a[mid] <= val && val <= a[mid +1]){ //value is between the cut for(int i = a.length – 1; i > mid + 1; i–){ a[i] = a[i – 1]; } a[mid + 1] = val; return a; } else if(val >= a[mid + 1]){ //search right side return insert(a, val, mid+1, end); } else { //search left side return insert(a, val, start, mid-1); } } |
question :
You have a list of sentences/words. How to find out the sub list that consists of a specific prefix? Ex: input: prefix="he", list = ["hello", "world", "hello world", "hey dude", "galaxy"….] output: ["hello", "hello world", "hey dude"] |
answer: Construct TRIE and search through it. |
answer: APEW KHABAR SEMUA.. |
answer: For a pair of prefix and list of sentences, wouldn’t it be just as efficient to just check the prefix against each sentence. If you are checking multiple prefixes constructing a trie would improve things. |
answer: Mostly the followup questions of any interview will be: imagie the dataset is big. Or whats the complexity & how will u improve it. So, its better to give the first answer as the best. :)Thats wat I did. Try creating indexes for your data to retrieve it faster. And as I already said, avoid naive approaches |
question :
Given a linked list containing integers as values, write an algorithm that detects if there is a loop or cycle in the list. |
answer: I wasn’t prepared enough and got this wrong, but apparently one solution involves creating two iterators, one slow and one fast, and seeing if the fast one "laps" the slow one. If they are never in the same place, there’s no cycle. |
answer: Another way is to look at the pointer references. Basically, if you store a temporary list of visited nodes you’ll have references to each one. Now the value they store may not be unique, but the memory address will be (it should be a new object). So if you encounter a duplicate reference/memory location you’ve got a loop since you’ve got two references to the same node (the original node and the looping pointer to it). |
question :
Given an inorder representation , how many BST’s can be formed from it. |
answer: 2^n – n …where n is the number of elements (nodes) |
answer: (2^n) – n …where n is the number of elements (nodes) |
question :
Sample question: "if the CEO can’t connect from his office but every other computer in the company can what do you do?" You are not allowed to go to his office to troubleshoot the problem. |
answer: I ran down everything I could possibly think of and don’t think I got it right. They never told me the answer. |
answer: Tell him to get his laptop to your desk. |
question :
Given an large list of unsorted numbers, find the smallest number. You can access the list only 3 numbers at a time, and keep moving forward 1 number at a time. |
answer: Otherwise called the sliding window problem |
answer: Use the selection sort and after the pass stop the iterating. Time complexity will be O(N) & only one swap. |
answer: Use the selection sort and after the first pass stop the iterating. Time complexity will be O(N) & only one swap. |
answer: Did they asked to write the code of the solution? or just pseudo code.And did they added any constraints? Otherwise this is pretty straight forward problem using Insertion sort. |
question :
Find the kth smallest number in an unsorted array with minimum complexity. |
answer: Use partitioning so that sorting is not required. |
answer: we can use max heap of size k.for more info http://www.careercup.com/question?id=14118753 |
question :
How do you conduct a survey to know how many number of cars sold in a particular city? what are the techniques do you use for the accuracy? |
answer: Question is related to market research, can be answered in different ways, it depends on individual approach to the market research. |
answer: the no of cars registered in RTO of the city would give the 99% accurate answer |
question :
What is router and cookie ? |
answer: I know about router but don’t know about cookie. |
answer: Router is a device which routes internet traffic.cookie is something tht which saves in server. |
answer: Cookie is something which is getting saved in client’s browser/machine so that server can identify the client. |
question :
What is bears and bulls in accounting ? |
answer: don’t know |
answer: The meaning of bull and bear is related to a business accounting.It is both inter related to supply and demand.If demand increases or supply falls and prices go up then its seem to be a Bull market.when there is a demand decreases or supply increases and prices go down then it is a Bear. |
question :
Reverse linked list recursively. |
answer: # A pythonic linked list.forward_list = { ‘value': ‘a’, ‘next': { ‘value': ‘b’, ‘next': { ‘value': ‘c’, ‘next': None } }}def reverse_list(node): ”’ Reverses a linked list. Returns the supplied node and the new head of the list. ”’ # The new head of the list. head = node # If we’re not at the end, reverse the next nodes and add this node to the # chain. if node[‘next’]: result, head = reverse_list(node[‘next’]) result[‘next’] = node node[‘next’] = None # If we’re at the end, this statement is the base case; return the newly # reversed list. return node, headdef print_list(node): print node[‘value’], if node[‘next’]: print_list(node[‘next’])# Test code.print ‘Forward list:’,print_list(forward_list)print# Print the reverse list.print ‘Reverse list:’,old_head, new_head = reverse_list(forward_list)print_list(new_head) |
answer: Node * reverse( Node * ptr , Node * previous) { Node * temp; if(ptr->next == NULL) { ptr->next = previous; return ptr; } else { temp = reverse(ptr->next, ptr); ptr->next = previous; return temp; }}reversedHead = reverse(head, NULL); |
answer: /* Jun Zheng, Rice Univ C++, Xcode 4.5.2 Reverse a linked list recursively Real interview question of Amazon & Schlumberger */ void reverseRec(node<T>* &phead){ if(phead==NULL ||phead->next==NULL) return; node<T>* p1=phead->next; node<T>* p2=p1->next; p1->next=phead; phead->next=NULL; phead=reverseRecHelper(p1,p2); } //Auxiliary method for void reverseRec(node<T>* &phead) node<T>* reverseRecHelper(node<T>* &p1, node<T>* &p2){ if(p2==NULL) return p1; node<T>* p3=p2->next; p2->next=p1; p1=reverseRecHelper(p2, p3); return p1; } |
question :
How many smaller cubes are completely invisible in a n*n*n rubic’s cube? |
answer: n^3- 6n^2The number of cubes are n^3(volume).The number of cubes exposing one or more sides( 6 *( n^2) – all cubes on the sides.)Number of invisible cubes are n^3- 6n^2 . |
answer: Isn’t the answer none since the question says "completely invisible"? every unit is visible by at least one side so any sub cube (made of these units) has a portion exposed. |
answer: N*N*N-(N*N*2+N*(N-2)*2+(N-2)*(N-2)*2) |
answer: (N-2)^3 |
question :
Find the maximum value in a stack, with constant complexity |
answer: keep track of the highest value when you do a pop and push into the stack. simple. |
answer: It’s easy to keep track of the highest value when you do push. But it gets tricky when you do pop. You may need two stacks to keep track of it. |
answer: @Jun: Where is the constant complexity?? You gonna push and pop every element or do you have any specific algo |
question :
How to build a dictionary in such a way that it’d be efficient to search for all valid words which are permutations of a given string? |
answer: Hash table |
answer: void print_in_order(Node* node){ std::stack<Node*> nodes; nodes.push(node); while(!nodes.empty()) { Node* temp = nodes.top(); if (temp) { cout << node->value << endl; nodes.push(node->left); nodes.push(node->right); } nodes.pop(); }} |
question :
Why did you relocated from your native place to this city? You do have better options available there. |
answer: I’ve completed my education from this city hence willing to continue here. It’ll be hard for me to go there and again stablish my self. |
answer: Ya though it will be a new experience… But the start from a new city or place charges more in terms of time and money….if i choose the place were i have born,brought up,staying from twenty years know how to manage the things in that place.. |
question :
Given the daily stock prices of a share during last 30 days, write a program to find out best buying and selling dates for maximum gain. The program should run with O(n) complexity. |
answer: find the difference of price change on everyday and store it in an array. i.e., something like: [2,0,-3,6,-1]Now find the sub array which has the more sum. http://en.wikipedia.org/wiki/Maximum_subarray_problem |
answer: @devsathish, I do not think so!Consider : {1,-4,5,6,-3,9,1,7}Maximum_subarray_problem would select {5,6,-3,9,1,7} where as the logical index for buying should be 1 and 5 respectively. |
answer: Much much simpler in O(n)Just make a new array which contains the "lookahead" view, where we can see, which potential highest value we can gaini in future.Another array just contains the lowest value so far. When the difference between the two arrays is max, there is the buying point. Selling point is, when the falling edge of the max array is reached. public void highestGain(int[] prices) { int[] maxPrices = new int[prices.length]; int[] minPrices = new int[prices.length]; maxPrices[maxPrices.length-1] = prices[prices.length-1]; minPrices[0] = prices[0]; for(int i = 1; i<prices.length; i++) { int right = prices.length-i-1; minPrices[i] = Math.min(minPrices[i-1], prices[i]); maxPrices[right] = Math.max(maxPrices[right+1], prices[right]); } System.out.println("MaxPrices: " + Arrays.toString(maxPrices)); System.out.println("MinPrices: " + Arrays.toString(minPrices)); // find when to buy (when the difference of min/max is highest) int maxDifference = maxPrices[0] – minPrices[0]; int maxDifferencePos = 0; for(int i=0; i<minPrices.length; i++) { int difference = maxPrices[i] – minPrices[i]; if(maxDifference < difference) { maxDifference = difference; maxDifferencePos = i; } } // Now find the falling edge of max prices – there was the last peak int sellPos = maxDifferencePos+1; int lastPrice = maxPrices[maxDifferencePos]; for(; sellPos < maxPrices.length; sellPos++) { if(lastPrice > maxPrices[sellPos]) { sellPos –; break; } } System.out.println("Ideal to buy/sell: " + maxDifferencePos + ":" + sellPos); } |
question :
Replace all spaces in a string by %20. Write production quality code in first attempt |
answer: count the number of spaces in the string, say this number is nallocate a new string whose length is the same + 2 * nmaintain two indices, i and j, i starts at the start of the original string and j starts at the start of the new stringwhile i is less than the length of the string: if symbol at i is a space: copy %20 to the new string at j, advancing j by 3 else copy symbol at i in string to symbol at j in new string, advancing j by 1 advance i by 1 |
answer: check out the code..http://justprogrammng.blogspot.in/2012/06/replace-all-spaces-in-string-by-20.html |
question :
First Round Questions (6 year Exp Software Engineer took the interview) 1)In a Given array which contains sorted numbers only one of number matches with that of Index. Find the number Not in O(N). 2)Derive a DataStructure to support the following operations Insert/Delete/Search/GetRandom Value in O(1) & O(logN) |
answer: Both are straightforward problems.Interviewer was genuine enough to guide when I was deviating from the answers.With Collaborative effort this was solved. Overall this interview lasted for 45 minutes |
answer: Problem1 can be solved via binary search. The index to find would be the "turning point" in the array, where all entries before it are smaller, and all entries after it are larger than the indices. Search can be done in O(LogN) |
question :
Write code to count the number of bytes used for the int data type. |
answer: int CountIntBitsF() { int x = sizeof(int) / 8; return x;} |
answer: ^^ Your answer is incorrect. Look closely at the question. |
answer: int *p;int count=(char *)(p+1) – (char *)(p); |
answer: void count_bytes_used() { int a = 66000, bytes=0; while (a > 0) { bytes++; a = a >> 8; } printf("BYTES USED: %d\n", bytes);} |
question :
Closest pair of points problem |
answer: Was able to explain the algorithm, but struggled in writing actual code |
answer: You don’t have to come up with the O(nlogn) solution. The naive approach (comparing every two points) in to nested for loops is good enough. explaining the O(nlogn) solution (divide and conquer) is a bonus, I don’t think that anyone really expects you to be able to write an implementation during an interview. |
answer: In Amazon they ask for real implementation over phone. |
question :
Given an integer array which consists of numbers from 1 to N with 1 number missing find the missing number. What will you do if 2 numbers are missing? |
answer: Given that the summation from 1 -> N = N(N+1)/2, we can use simple math to get a solution in O(n) time.We know that our array is "missing" a number, so it’s length "L", is N-1. So we know that the summation for our array if it were not missing the value X could be calculated as N(N+1)/2, or (L+1)(L+2)/2. For a given array with length L, all we need to do is calculate what the expected summation is, iterate over the array and find the actual summation, then calculate the difference.public int findMissingValue(int[] sequence) { int length = sequence.length(); int expectedSum = ((length + 1) * (length + 2)) / 2; int actualSum = 0; for (int i = 0; i < length; i++) { actualSum += sequence[i]; } return expectedSum – actualSum;} |
answer: You have an array of length N filled with numbers 1 through N+1 with one number missing.1. bitwise xor all numbers 1 to N+12. bitwise xor all numbers in the array3. bitwise xor the above two numbers to get the missing number, as duplicates will cancel outIf two numbers are missing this approach and the sum approach fail. In this case I can’t think of a faster way than sorting the list. |
answer: For 2 number missing..First split up the array into halffrom first half find the first missing numberand second half find the second missing number.If 2 missing numbers are in first half then again divide the first half into 2 half and find it. |
answer: Use a bitmap: keys are 1 to N and values are true/false.Iterate over the array and populate the bitmap.Iterate over the bitmap and the missing numbers are those that have the value == false. |
question :
Given ‘n’ integers, print the numbers given in a range |
answer: Use binary search tree to save the n numbers and print all the numbers that fall between the given range. |
answer: The question doesn’t say the numbers are sorted, so it would be cheaper to do a linear search. If the numbers were sorted then do a binary search for either ends of the range and print the numbers in between. |
question :
Find the longest palindrome in a string |
answer: O(N^2) solution in java://Now implement the improved methodpublic static String LongestPalindromeImprove(String in){ char[] input = in.toCharArray(); int longestStart = 0; int longestEnd = 0;//we also need global start/end to keep track of the current best as we process //now the key is to scan from mid to both ends for(int mid=0; mid<input.length;mid++)//we name it as mid for easy interpretation { //for odd case int left = mid; int right = mid;//for example 12321 when we choose 3 as mid while(left>=0 && right<input.length)//make sure both indexes are valid { if(input[left]==input[right])//if still palindrome match by one step further each loop cycle { //we need decide if to update global start/end if(right-left>longestEnd-longestStart)//the longer is found! { longestStart = left; longestEnd = right; } } left–; right++;//sorry added in wrong place, should be in either case per mid choice } //well for even case we need replicate the previous code by making one change left = mid; right = mid+1;//for example 123321 when we choose 33 as mid while(left>=0 && right<input.length)//make sure both indexes are valid { if(input[left]==input[right])//if still palindrome match by one step further each loop cycle { //we need decide if to update global start/end if(right-left>longestEnd-longestStart)//the longer is found! { longestStart = left; longestEnd = right; } } left–; right++; } //do not forget to increase right and decresea left!!! } //after the loop we return return in.substring(longestStart, longestEnd+1);}I also made a demo video to show the whole process to solve this problem with a comparison naive (O(N^3)) method and a test case at http://youtu.be/UhJCXiLSKv0 |
answer: Check out the nice C code..http://justprogrammng.blogspot.com/2012/05/find-longest-palindrome-in-string-onn-c.html |
answer: /* * To change this template, choose Tools | Templates * and open the template in the editor. */package towerofhanoi;import java.util.Enumeration;import java.util.Hashtable;import java.util.Vector;/** * * @author sanal */public class PalindromeEx { public boolean isPalindrome(String str){ char[] chars = str.toCharArray(); int left = 0; int right = chars.length-1; int mid = chars.length/2; for(left=0;left<mid;left++,right–){ if(chars[left] != chars[right]){ return false; } } return true; } public String getLongestPalindrome(String sentence){ String palindrome=""; for(int base=0;base<sentence.length();base++){ for(int end=base+1;end<=sentence.length();end++){ if(isPalindrome(sentence.substring(base, end))){ if(palindrome.length()<sentence.substring(base, end).length()){ palindrome = sentence.substring(base, end); } } } } return palindrome; } public static void main(String[] args) { System.out.println((new PalindromeEx()).isPalindrome("aabaa")); System.out.println((new PalindromeEx()).isPalindrome("abba")); System.out.println((new PalindromeEx()).isPalindrome("abca")); System.out.println((new PalindromeEx()).isPalindrome("abcaabbaacba")); System.out.println((new PalindromeEx()).getLongestPalindrome("abcaabbaacba")); System.out.println((new PalindromeEx()).getLongestPalindrome("abcaabbabcba")); System.out.println((new PalindromeEx()).getLongestPalindrome("a")); System.out.println((new PalindromeEx()).getLongestPalindrome("aa aa b")); }} |
question :
Find all prime numbers no bigger than x. |
answer: Bertrand’s postulate (actually a theorem) states that if n > 3 is an integer, then there always exists at least one prime number p with n < p < 2n ? 2. A weaker but more elegant formulation is: for every n > 1 there is always at least one prime p such that n < p < 2n.So if I am given a number, say n, than I can check in the range (n, 2*n) [open interval excluding n and 2*n]int GetNextPrime(int n){ bool isPrime = false; int i = n; for (; i < 2 * n; ++i) { // go with your regular prime checking routine // as soon as you find a prime, break this for loop }} |
answer: the question says "find all primes NO BIGGER THAN X". it doesn’t say "find a prime bigger than x". |
answer: http://www.factmonster.com/math/numbers/prime.htmlA prime number can be divided, without a remainder, only by itself and by 1. For example, 17 can be divided only by 17 and by 1.Some facts:The only even prime number is 2. All other even numbers can be divided by 2.If the sum of a number’s digits is a multiple of 3, that number can be divided by 3.No prime number greater than 5 ends in a 5. Any number greater than 5 that ends in a 5 can be divided by 5.Zero and 1 are not considered prime numbers.Except for 0 and 1, a number is either a prime number or a composite number. A composite number is defined as any number, greater than 1, that is not prime.To prove whether a number is a prime number, first try dividing it by 2, and see if you get a whole number. If you do, it can’t be a prime number. If you don’t get a whole number, next try dividing it by prime numbers: 3, 5, 7, 11 (9 is divisible by 3) and so on, always dividing by a prime number |
answer: Tip: (n*6)+/-1 |
answer: This is the fastest method if you have a bound: http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Implementation |
question :
How to search a certain string inside a longer string consist of random data? |
answer: Create a hashtable from longer string, Compare it with Second Search String. |
answer: <cstring>const char * strstr ( const char * str1, const char * str2 ); char * strstr ( char * str1, const char * str2 );"Locate substringReturns a pointer to the first occurrence of str2 in str1, or a null pointer if str2 is not part of str1.The matching process does not include the terminating null-characters." |
question :
What is the difference between a risk and an issue? |
answer: This is classic project management professional terminology, which I knew. But since I’m not a PMP I didn’t know the precise definitions so I didn’t try to bluff it. In the real world the two things are so different that you can’t really point out what the differences are. I was left doing a goldfish impression – mouth opening & closing. |
answer: An issue is an actual problem which is (negatively) impacting your project.A risk is an unknown or potential future event — can have negative OR POSITIVE impact (yes!) and may or may not occur. |
answer: In Jeopardy you wouldn’t get the money! That doesn’t say what the difference is, it says what each of them are, but yes a reasonable response can be extrapolated from that (my resume did say "attention to detail" even if it didn’t say "PMP").Non-PMP’s will probably laugh at the concept that risks can be positive because in any normal dictionary they are only about negative things ("exposure to the chance of injury or loss; a hazard or dangerous chance"). That PMP speak doesn’t term them "uncertainties" instead of "risks" is risible. |
question :
Write a function which takes two strings as parameters and returns a string of common characters between the two strings but no duplicates. Use hash table to implement the algorithm. |
answer: (I chosed C# to do that) |
answer: Convert the strings into character arrays and then add the first string in Hashtable by looping through all characters of array and adding them in the Hashtable. Then in another loop check if characters of the second string are contained in Hastable. Complexity would be O(length of larger string)…. I think it should work… |
answer: Actually you need to take care of the duplicates otherwise you will get duplicates. The following code provides correct answer.public class commoncharnodup { private static void noDup(String in1,String in2) { Hashtable inhash=new Hashtable(); StringBuilder commonChar=new StringBuilder(); for(int i=0;i<in1.length();i++){ if(!inhash.containsKey(in1.charAt(i))){ inhash.put(in1.charAt(i), i); } } boolean added=false; for(int i=0;i<in2.length();i++){ if(inhash.containsKey(in2.charAt(i))){ commonChar.append(in2.charAt(i)); added=true; } if(added==true) {inhash.remove(in2.charAt(i)); added=false; } } System.out.println(commonChar); } public static void main(String[] args) { noDup("aabcd","aabd"); }} |
question :
given non-zero number array A, create array B where B[i] = product of all elements in A except A[i]. |
answer: No division, minimize number of multiplications. |
answer: #include <iostream>using namespace std;int main() { int A[5] = {1,2,3,4,5}; int B[5] = {1,1,1,1,1}; for (int i = 0; i<5 ; i++) for(int j=0 ; j< 5; j++) { if (i != j) { B[i] *= A[j]; } } for (int k = 0 ; k < 5;k++) { cout<<B[k]<<", "; } cout<<endl; return 0;} |
answer: That will use n^2 number of multiplications.Using a table with size i,j where i<n, j<n and store the result of t[i,j] = a[i] *a[j] .It can reduce the number of multiplications to (n^2/2 + n/2). |
answer: The fundamental idea behind this problem is to break it down into smaller pieces and solve those smaller pieces, dynamic programming. So in this case lets consider a list A:A = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]Notice that B[4], B[5] and B[6] are:B[4] = (A[1]*A[2]*A[3]) * (A[5]*A[6]*A[7]*A[8]*A[9]*A[10])B[5] = (A[1]*A[2]*A[3]*A[4]) * (A[6]*A[7]*A[8]*A[9]*A[10])B[6] = (A[1]*A[2]*A[3]*A[4]*A[5]) * (A[7]*A[8]*A[9]*A[10])So each step is represented as the product of the two numbers. And the component part of these products grow in a known way. So we should be able to do the computation in O(N) time with 2N operations.Here is some code in python. I did this quickly so it might not be the most elegant code but it should demonstrate the idea:a = [1,2,3,4,5,6,7,8,9,10]def cct(i,b) : return str(i) + str(b)def make_key(a): if a: return reduce(cct,a) else: return ”partial_values = {}def pi(a): if not a: return 1; la = len(a) hash_str = make_key(a) if la == 1: partial_values[hash_str] = a[0] return a[0] else: if partial_values.has_key(hash_str): return partial_values[hash_str] else: value = a[0] * pi(a[1:]) partial_values[hash_str] = value return valuedef f(a): results = [] for i in range(len(a)): beginning = a[0:i] beginning.reverse() end = a[i+1:] results.append( pi(beginning) * pi(end) ) return results |
answer: You are given an array A of length N. Out of this one array make two more:1. B, whose n-th element is the product of the first n numbers in A.2. C, whose n-th element is the product of the last N-n numbers in A.To compute the wanted array D do D[i] = B[i] * C[i+1].We can construct B, C, and D in linear time so the whole thing is linear. |
question :
given an array of integers(positive or negative), and two integers x, y. write a function that can find a subarray whose sum equals to x and product equals to y |
answer: It’s a recursive backtracking problem. Create a helper method so you can keep a start index through the recursion. Your base case is when you’ve reached the end of the array. For each recursive call you have two options for the number at your start index, either chosen or not. If chosen, manipulate x and y for the next recursive call, either subtracting or dividing (be sure to do modulo to ensure the number is a factor of y). If not chosen, pass x and y back in as they are, but increment start.The logical or of the chosen and not chosen paths should be the return value from the recursive helper method. For the base case the return value is whether or not both x and y equal zero. |
answer: Slight correction to above — you’re not returning a boolean value, so when doing the logical or, return the array if it’s true — or null if false… same for comparisons of x and y to zero. |
answer: 1. insert all array data into hash table.2. Read first/next element of array. p = x- (first_num)3. search p in hash table4. If found return that. else go to step 2 till array exhausts.do simillar step for finding dividend. |
answer: Subarray suggests a consecutive array within the original array. Let’s say this is the case.Say you are given array A of length N. Create two more arrays:1. B, whose n-th number is the sum of the first n numbers in A.2. C, whose n-th number is the product of the first n numbers in A.Say we are given subarray indices i < j. The sum of this sub-array is B[j] – B[i] and the product of this sub-array is C[j] / C[i].Note that we want B[j] – B[i] = x or B[j] = x + B[i], and also C[j] / C[i] = y or C[j] = y * C[i]. This suggests an algorithm. Create two more arrays:3. B2 whose n-th number is x + the n-th number in B.4. C2 whose n-th number is y * the n-th number in C.Now we look for collisions:1. Check for collisions in B and B2, that is B[j] = B2[i] = x + B[i]2. Check for collisions in C and C2, that is C[j] = C2[i] = y * C[i]It goes without saying that we want j > i in these collisions. We can find them in linear time by using a hashmap. Store the contents of B2 into a hashmap and iterate over B checking for collisions. Do the same thing with C and C2. The collisions will return pairs of indices (i, j). What do these mean? Collisions in B and B2 will produce sub-arrays that sum to x. Collisions in C and C2 will produce sub-arrays that multiply to y. All we do now is check for collisions between these. We can again use a hashmap.All of the steps are linear so the algorithm is linear. |
question :
How would you reverse a linked list? |
answer: This tutorial answers your question:http://youtu.be/LgapVjJYxqc |
answer: For a singly-linked list consiting of n linked nodes…i <– n-3;while ( i > -2) { node[i+2].next <– &node[i+1]; i = i – 1;}node[0].next <– null; |
answer: dave, the tricky answer given below is not acceptable in interview as well as in real programming. Please dont take these words as negative but try formulating solutions which are simple to understand and elegant. for example the invariants in above code and termination condition of -2 is not good.for example you can write –Node* prev = &head;Node* curr = prev->next;while(curr) { Node* tmp = curr->next; curr->next = prev; prev=curr; curr = tmp;}return prev; |
question :
Find the index of an element in a matrix which has been sorted, if can’t find the element return (-1, -1) |
answer: Two binary search will do. O(log(m) + log(n)) |
answer: The above makes no sense. You aren’t looking for a tuple, you are looking for an integer in a matrix whose rows and columns are individually sorted. This is the solution:Say looking for n.1. Binary search the top-most row. If found, good. Otherwise, discard the top row and discard columns starting with a number bigger than n (to the right of where the search for n ended up).2. Binary search the left-most column. If found, good. Otherwise, discard the left-most column and all rows starting with a number bigger than n (below of where the search for n ended up).3. If cells left go to 2, otherwise return "not found" |
question :
Given an array where each element is a 2-d tuple such as (int, a percentage), develop an algorithm which returns a weighted random number in the array where weights are the percentages. |
answer: All percentages add up to 100% in the array. |
answer: If the percentage is an int as well, like 30 then we can just allocate an array of length 100 and for each pair (n, p) insert n into the array p times. Randomly picking an element from this array will produce the desired result.If the percentages can be rational numbers we first modify the array to include a rolling sum so [(1, 20%), (2, 30%), (3, 50%)] becomes [(1, 20%), (2, 50%), (3, 100%)]. Now re get a random number between 0 and 100 and do a binary search in this new array on the second number in each pair, returning the first number once we find the correct range. |
question :
How would you traverse through a binary search tree and print out each element in order? |
answer: Use a queue and store all the current node’s children in the queue. Loop until the queue is empty. |
answer: If by in order you mean InOrder traversal:- You could traverse the tree very easily using recursion.- If you’re not explicitly allowed to use recursion. You could use a Stack to simulate recursion- If you’re not allowed to use a Stack to simulate recursion, you could walk through the tree and "rebuild" it so that it becomes a "vine" (almost a linked list) with the nodes reordered for inorder traversal and then walk through it. |
answer: No, the interviewer did not mean inorder traversal. You have to print the elements in order as in the root first then its left element and then its right element, then the left elements right element, ect. I thought recursion would work at first too, but it doesn’t because you will need to recurse all the way through either the left or right node and that’s not correct. You basically have to go to the left then the right and then the left again to get its children. This can’t be done using a stack either because you would get the wrong order. This problem is similar to BFS (breadth first search) – its pretty much that exact problem and that’s why a queue is used. |
question :
Find the numbers in an array that appear an odd number of times. |
answer: I used a hashtable and stored all the values into it with a key and value, value being the number of times it appears. Then I looped through the hashtable checked if mod(value) == 1 or 0. If 1 (odd) then save the key it into an array |
answer: If you are given that there’s only one element duplicated an odd number of times, you can simply XOR all the elements together. The resulting value is the element that was repeated an odd # of times.This works because A XOR A = 0. |
answer: To Anonymous:There could be several values that are have an odd number of duplicates. Using XOR wouldn’t work because you would get a weird XOR combination of all the odd number of duplicates. Nice thinking though; your approach was very interesting and outside the box |
answer: Make a hashmap.Iterate through the array.If the element is in the hashmap, remove it.If it’s not in the hashmap, add it.Now the only elements in the hashmap are ones that appeared an odd number of times. |
question :
Design a stack with min(stack) operation in constant time |
answer: The idea is to have a "current minimum" variable that you update on push. The trick is to save this current minimum with the node on push, so that once you pop you get the old "current minimum". |
answer: Using temporary variable is OKAY.But if pop operation is performed on curr minimum,it would be O(n) to update the new minimum |
question :
Given a string "aaabbbcc", compress it, = "a3b3c2" . Given that output string’s length is always smaller than input string, you have do it inplace. No extra space |
answer: public static String cstr(String a){ if(a.length()<2){return a;} if(a.length()==2){if(a.charAt(0)==a.charAt(1)){return a.charAt(0)+"2";}else{return a;}} for(int i=0;i<a.length();i++){ int c=i+1; while(c<a.length()&&a.charAt(c)==a.charAt(i)){ c++; } if(c-i!=1){ a=a.substring(0,i+1)+(c-i)+a.substring(c);i++; } } return a;} |
answer: #include<stdio.h>#include<stdlib.h>#include<string.h>#define STR_SIZE 26int main(){ /* Current char sequence tracker */ char *c = NULL; char *b = NULL; char *str = (char*)malloc(STR_SIZE * sizeof(char)); if(NULL == str) return -1; memcpy(str, "aaaabbbcceeeeefffffff", 26); b = c = str; printf("Input: %s\n", b); while(*str) { if(*(str+1) != *str) // Repeat sequence ends { // Add 48 so the count gets printed as a char *(c+1) = ((str-c+1)+48); // Updated count, copy rest of the string starting after the count position memcpy(c+2, str+1, strlen(str)); // Update c to point to the new char repeat sequence c = c+2; } str++; } /* b was initialized to point to str up top, proving it was done in place */ printf("Output:%s\n", b); free(b); b = NULL; return 0;} |
answer: String test="aavvvqwqaa"; int count=0,start=0,end=0; int length=test.length(); for(int i=0;i<length-1;i++){ if(test.charAt(i)!=test.charAt(i+1)){ end=i; test=test+""+test.charAt(i)+( end-start+1); count=count+(end-start+1); start=end+1; } } System.out.println(test); if(count<length){ test=test+test.charAt(count)+(length-count); } System.out.println(test.substring(length,test.length())); |
answer: Rohan: What if I give you the string "aaaaaaaaaa"? Your solution will print "a:", not "a10". |
answer: in java, if you give me a String str="aaabbbcc";you can’t modify the str as all, then how can you do it in place?I assume I can go through the str, and store the new string such as "a3b3c2"anyone can explain to me? |
answer: java inplace public void compress(char[] str) { if (str != null && str.length > 1) { for (int last = 0, curr = 1, count = 1, tail = 0; curr < str.length;) { for (; str[curr++] == str[last++] && curr < str.length; count++); //situation where the string is like ab should not generate a1b1 //which is longer then original array. simillar case for aab if (count > 1) { str[tail++] = str[last]; str[tail++] = (char) count; count = 1; } last = curr; curr++; } } } |
answer: Need to delimit the array public void compress(char[] str) { if (str != null && str.length > 1) { int tail = 0; for (int last = 0, curr = 1, count = 1; curr < str.length;) { for (; str[curr++] == str[last++] && curr < str.length; count++); // situation where the string is like ab should not generate // a1b1 // which is longer then original array. similar case for aab if (count > 1) { str[tail++] = str[last]; str[tail++] = (char) count; count = 1; } last = curr; curr++; } str[tail] = ‘\0′; } } |
answer: small correction – public void compress(char[] str) { if (str != null && str.length > 1) { int tail = 0; for (int last = 0, curr = 1, count = 1; curr < str.length;) { for (; str[curr++] == str[last++] && curr < str.length; count++) ; // situation where the string is like ab should not generate // a1b1 // which is longer then original array. similar case for aab if (count > 1) { str[tail++] = str[last]; str[tail++] = (char) (count + ‘0’); count = 1; } last = curr; curr++; } str[tail] = ‘\0′; } } |
answer: This solution covers all cases..http://justprogrammng.blogspot.in/2012/06/amazon-interview-string-compression-c.html |
answer: Here is a recursive code which considers all cases…http://justprogrammng.blogspot.com/2012/06/amazon-interview-string-compression-c.html |
answer: Try this.. it generates the desired output in Java/** * * @author Sourabh Mishra * Class which handles compression of a string replacing the occurrences of characters * with the character followed by its count in the input string * */public class StringCompressor { /** * Method takes input as a string and replacing the occurrences of characters * with the character followed by its count in the input string * @param data String * @return */ public String compressString(String data){ StringBuilder outBuilder = new StringBuilder(); char prevChar = data.charAt(0); int counter = 0; char currChar; int length = data.length(); for(int i=0; i< length; i++){ currChar = data.charAt(i); if(currChar == prevChar){ counter++; // For the last unique characters if(i == length-1){ outBuilder.append(currChar); outBuilder.append(counter); } continue; } else { outBuilder.append(prevChar); outBuilder.append(counter); prevChar = currChar; counter=1; } } return outBuilder.toString(); } /** * @param args */ public static void main(String[] args) { StringCompressor sc = new StringCompressor(); System.out.println(sc.compressString("aaabbbcc")); }} |
question :
– If 2 trains depart at the same time from 2 places 65 kilometers apart and one goes at 80 km/h and another one at 50 km/h when will they meet |
answer: 40 and 25 |
answer: they will meet 30 minutes later |
question :
Test if 2 sort arrays contained each other |
answer: what the heck does "contain each other" mean? given two sets, either s1 is a subset of s2, s2 is a subset of s1, they are equal, or they are not equal or subsets of each other. so the only way they can "contain each other" is if the are equal, and i don’t think that’s what the question is asking.the question is probably asking if one sorted array is contained in another sorted array. |
answer: Way to be an ungrateful j3rk, Jeff. You obviously understand what I wrote (even though it’s bad English). Just kindly clarify it in your comment so that other people can see. That’s how you respond to a stranger whose input is helping you in an interview. You’d better not show this side of you during the interview. |
question :
Write the code for the preorder traversal of a tree. |
answer: using recursionpublic static void preorderTraversal(Tree T,Node root){ if(root==null){ return "empty tree";}else{ visit(T,root);preorderTraversal(T,T,leftChild(root));preorderTraversal(T,T,rightChild(root));}} |
answer: public static void preorderTraversal(TreeNode node) { Stack<TreeNode> s = new Stack<TreeNode>(); while (node != null || !s.isEmpty()) { while (node != null) { visit(node); node = node.left; } if (!s.isEmpty()) { node = s.pop(); node = node.right; } }} |
answer: Sorry I forgot to push the node into the stack after visited it |
question :
How would you find the common primes in two integers ? |
answer: Compute the GCD of the two numbers using Euclid’s algorithm.Prime factorise the GCD. |
answer: GCD(int j, int i){ //assume i>j while(j!=0){ int temp=i%j; int i=j; int j=temp; } return i;} |
question :
Merge two sorted linked lists with unique integers. |
answer: Maintain two pointers, one for each list. Loop until atleast one of the two pointers is null, while adding the smaller of the two pointer values to the resulting linked list. Once one of the two pointers is null, add the remaining elements of the other pointer to the resulting linked list. Return the list. |
answer: public void Merge(LinkList list1, LinkList list2) { if (list1.head == null && list2.head == null) { System.out.println("Empty list"); //checks if list is empty } if (list1.head == null) { list2.printList(); } if (list2.head == null) { list1.printList(); } LinkList list3 = new LinkList(); Node a = list1.head; Node b = list2.head; while (a != null && b != null) { if (a.value < b.value) { list3.insert(a.value); a = a.next; } else if (a.value > b.value) { list3.insert(b.value); b = b.next; } else if (a.value == b.value){ //inserts only unique value to the merged list list3.insert(a.value); a = a.next; b = b.next; } } if (a == null) { while (b != null) { list3.insert(b.value); b = b.next; } } if (b == null) { while (a != null) { list3.insert(a.value); a = a.next; } } list3.printList(); } |
question :
Which number is bigger: 5/6, 3/4, 4/7, 4/9, or 9/11 |
answer: 5/6 is the largest fraction in the set…. |
answer: 3/4, 4/7, and 4/9 are clearly smaller than 5/6 and 9/11, so they are eliminated.So which is bigger, 5/6 or 9/11? You can look at it as which is smaller, 1/6 or 2/11. 2 does not fit into 11 six times, so 1/6 is smaller. Since 1/6 is smaller than 2/11, 5/6 is larger than 9/11. |
answer: Do you remener any other interview questions?Thanks |
question :
Write a function in java to calculate all the possible palindromes in a string. |
answer: Simple calculate all the possible substrings, and write a helper method to check if each substring is a palindrome. |
answer: Please see the link here . It has the explanation and code for the problemhttp://www.nobrainer.co.cc/2012/02/find-all-palindromes-in-given-string.html |
question :
You got some baby bottle samples. You would like to know the max height you can drop it without breaking the bottle. Let set the unit as 1 foot. And the highest height you can reach is at N feet. So how would you find the (max) safe height? |
answer: It’s a binary search problem. Find n/2. Try it. If broken, repeat same process for 1~(n/2-1). The time complexity is O(log n). Then explain my pseudo codes. |
answer: dude..you must be very clever…i got an interview and had a hard time answering those questions.. |
answer: If "some" is large enough, drop the bottles in 1-foot increments up to N all at the same time. Or at least use your dual hands in parallel. |
answer: From Half the distance(N/2) drop a bottle,If breaks (Drop the bottle at N/4 i.,e going downwards)If Does not Break( Drop the bottle at N/2+N/4 = 3N/4 i., going upwards )This way you should be able to find the max height where a bottle breaks. |
question :
(following the previous one) You got only ONE baby bottle sample. You would like to know the max height you can drop it without breaking the bottle. Let set the unit as 1 foot. And the highest height you can reach is at N feet. So how would you find the (max) safe height? |
answer: Do a linear search. Time complexity is O(N). Only need ONE bottle. |
answer: Drop the bottle start from down i.,e from 1 foot and traverse upwards in increments of 1 until height reaches N. (LInear search) . |
question :
(following the previous one) You got only TWO baby bottle sample. You would like to know the max height you can drop it without breaking the bottle. Let set the unit as 1 foot. And the highest height you can reach is at N feet. So how would you find the (max) safe height? (This is the one I think is kind of brain-teaser one.) |
answer: I figure out a O(x) solution, where x is n/2, but it’s still O(n) theoretically.My interviewer insist there exists a better answer (in terms of time complexity). But he refuse to tell me the answer nor hint, for example, what will that time complexity be in this solution. I wish someone can help on this problem. |
answer: I am thinking if you have 2 bottles you1. use the O(log n) approach until the bottle breaks to find better bounds2. use linear search on those new bounds to find the answerSo worst case is O(n/2) best case is O(log n) |
answer: The best solutio with two bottles is radical N. |
answer: Well you could keep doubling the height 1,2,4,8… so on till the first bottle breaks. Then start the linear increment for the next bottle from the point before the previous bottle broke. Say it broke at 32, then use 16 as the new start and use linear increments of 1ft 17,18,19..so on. |
answer: Increase height by squareroot of N with first bottlelinear search with second bottleO(n^1/2) complexity |
answer: I have had this question before.Assume you have a number, D, that is the max bottle drops you can use to find the answer.To do this you would start at floor D and drop the bottle. If it breaks, then you do a linear search from floor 0 to D with the other bottle (thus finding the solution in, at most, D attempts).If it doesn’t break, move up D-1 floors. It must be D-1 because if the bottle breaks, you will only have D-1 attempts left to do the linear search. This is because you used one attempt back at the previous floor. If it breaks you do the linear search from floor D to your current floor.You repeat this process (always moving up one less floor) until you run out of attempts.If you write out this in an equation, the highest floor you can get to is given by the sum:D(D+1)/2 >= NSolve for whatever particular N, and you get the best possible D.For example, on a 100 story building you can find the highest floor with at most 14 drops. |
answer: Use Binary search until 1 bottle breaks then perfrom linear search. |
answer: assume we do linear probing with the first bottle and use the second to narrow down. Then, assuming max height = N total number of steps required =N/x + x. Objective is to minimize x. So, get differential and equate to 0. x = N^(1/2) |
question :
trees..in order pre order |
answer: void inorder(tree t){ if(t == NULL) return; inorder(t -> left); cout << t -> left << " "; inorder(t -> right);}void preorder(tree t){ if(t == NULL) return; cout << t -> left << " "; preorder(t -> left); preorder(t -> right);}Since I’m already this far here is post order as well:void postorder(tree t){ if(t == NULL) return; postorder(t -> left); postorder(t -> right); cout << t -> left << " ";} |
answer: CORRECTION:It should be printing t -> val, not t -> left Sorry!void inorder(tree t){ if(t == NULL) return; inorder(t -> left); cout << t -> val << " "; inorder(t -> right);}void preorder(tree t){ if(t == NULL) return; cout << t -> val << " "; preorder(t -> left); preorder(t -> right);}Since I’m already this far here is post order as well:void postorder(tree t){ if(t == NULL) return; postorder(t -> left); postorder(t -> right); cout << t -> val << " ";} |
question :
You are given a Binary Search Tree of ints with duplicate entries. You are guaranteed that if an element has a duplicate entry, it is in the right subtree of that element. Write a function to count the total number of duplicates. (note, if a tree contains the same element two times, the count of duplicates is 1, not 2) |
answer: An inorder traversal of the tree will yield repeated elements one after the other. Write an inorder traversal recursively, and modify it to pass in the previously seen element. If the current element is equal to the previously seen element, increment the count by 1. |
answer: The follow code could do the trick …int DupCount( Node *root ){ int count = 0; DoDupCount(root, count); Return count;}void DoDupCount(Node *root, int &count){ if (root == NULL ) return; // traversal , go left first DoDupCount(root->left, count); Bool flag = false; // traversal, go right until met different node While(root->right != NULL && root->right->data == root->data ) { flag = true; root= root->right; } if (flag) count++; DoDupCount(root->right, count);} |
question :
Design a data structure to store strings efficiently for following operations : 1. IsPrefix (s1, s2) : Is s1 a prefix of s2. 2. IsEqual(s1, s2) : Are s1 and s2 equal. 3. common prefix(s1, s2) : Return the common prefix of the given strings s1 and s2. |
answer: Reverse the strings and use a suffix tree. (A suffix tree is a type of radix tree.) |
answer: Suffix Array ? |
question :
1) how do find out if there is a path from root to leaf whose summation= given number? |
answer: Here is my solution, please do let me know if it works.class Node{ public int value; public Node left; public Node right;}boolean function pathExists(Node node, int givenNumber){ //first case, if the node is null, conclude false if( node == null ){ return false; } //if reach leave if( node.left == null && node.right == null){ //decision bases on the remaining and the leaf’s value return (node.value == givenNumber ); } //keep searching the remaining in node’s children return pathExists(node.left, givenNumber – node.value) || pathExists(node.right, givenNumber – node.value);} |
answer: @Duy: we should not check for leaf node since the path may be before we reach leaf as well. so , with a simple change, this should work:if( node == null ){ return false; } //if reach leaveelse if (node.value == givenNumber ){ return true; } //keep searching the remaining in node’s children else return pathExists(node.left, givenNumber – node.value) || pathExists(node.right, givenNumber – node.value);} |
question :
Find nth last number in a singly linked list. |
answer: static List returnNode = null;//define as class scope variable//for this recursive call, very last node (null) return 0, and all preceding nodes gets 1+ higher indexesstatic int FindNthLast(List L, int N){ if (L == null) return 0; else { int nextLastIndex = FindNthLast(L.Next, N); //If we found the Nth last node, we need assign List value to class-scope returnNode if (nextLastIndex + 1 == N) returnNode = L; return 1 + nextLastIndex; }}//after executing FindNthLast(List, N), returnNode.value is the nth last value we are looking for in the List |
answer: The problem here is that we can only start from the head to tail. The previous code is one of the solutions. Another non-recursive solution is that reverse that linked list (http://www.mytechinterviews.com/reverse-a-linked-list) then perform a simple scan to get the nth number from the head. I guess the running time for my solution is O(n). |
answer: Traverse twice through the LL. The first pass will return number of elements. The second pass with the number of an element (starting from zero) subtracted from the size of the list will find the Nth element. O(n). Why make it too complicated? |
answer: Have two pointers with a difference of n.When pointer1 is at head, pointer2 is at element n from the head.Traverse the list moving pointer1 and pointer2 until pointer2 reaches end of the list at which case pointer1 is pointing to element at N from end. |
answer: Yes, using two pointers is a good way: public static Node getNthLast(LinkedList ll, int n) { Node node1 = ll.getHead(); Node node2 = node1; int i = 0; while(node1 != null) { node1 = node1.getNext(); if(i >= n) { node2 = node2.getNext(); } i++; } return node2; } |
answer: Node node1 = root; Node node2 = node1; while (num– > 0) { node2 = node2.getNext(); } while(node2 != null) { node1 = node1.getNext(); node2 = node2.getNext(); } System.out.println("\n\n Last 5th number is : " + node1.getValue()); |
question :
How will you check to see if two integer arrays have any common elements? |
answer: My solution was this…If the arrays are A, B. Load the data in array A into a Hash Table (excluding any duplicates in the array) Now take every element in array B and try to look up the hash table if there are any entries…if there are any collisions, we can say that, they have common elements. I know this can be done in much better ways which I dont know |
answer: The question essentially is asking you to find the intersection between two arrays:You can traverse the two arrays in O(N) then simply return the common elements (although thats not asked).int i = 0; j = 0;while(i < arr1.length && j < arr2.length) { if(arr1[i] == arr2[j]) { vector.add(arr1[i]); i++; j++; } else if (arr1[i] > arr2[j]) { j++; } else { i++ }return vector; |
answer: @SolutionYodaYour solution would be correct if the arrays are sorted… |
answer: Soln1:1) Sort array1 and array22) Follow the implementation by @solutionYoda.Soln2:1) Store the array1 value in hashmap2) Iterate the array2 and check if the element is existing in hashmap. If yes then print the value. or you can change the value of the map.put(key,"true").Time complexityO(m) for array1 to put in hashmapO(n) for array2 and check it in hashmap.plus some operation to change the value for matched value.Space ComplexityO(m) for the array1.Always choose smaller array to store the value in hashmap. |
question :
Describe data structure for Shuffle operation in a music player |
answer: There are 2 operations that the expected data structure should facilitate:1) Randomly select an not-played song.2) Determine if a song was played or not.I think we might to make 2 separated list, one contains the songs that are already played and the other contains the songs that are not played yet. Then using the random generator to pick one song from the unplayed list and move it to the played list once it is played.Any other better solution? |
answer: Implementation in java1) Select a random number Math.random(). It returns a number between 0 and 1 and it is a a double value.2) Muliply that number with 1000 . It returns a integer value.3) Suppose x is length of array that contain songs, divide step2 by x.4) the resultant value is the song to be played.5) You can keep a counter and increment the counter if the song is played( iTunes).double d= Math.random();int v=(int)d*1000;int x=songArray.length();int nextSong = v % x // This value is always less than length of array.player.play(songArray(nextSong)); |
question :
Given an array of integer and a value(integer), find all the pairs of integers in the array that sum up to the value. |
answer: You can solve this using a kind of binary search of the array as long as it is sorted.int FindPair(int x[], int size, int findMe) //x is sorted array, size is num elements in x{ int start = 0; int end = size-1; for (int i = 0 ; i < size ; i++) { int result = x[start] + x[end]; if ( result == findMe ) return findMe; //found a pair! else if ( result > findMe ) end–; else start++; }}Of course, you’d probably want to store the positions of start and end for each pair found instead of just returning the value, and you’d also want to call FindPair from another function which can save each pairing found. |
answer: Instead of for (int i = 0 ; i < size ; i++)it should bewhile( start < end ) |
answer: You can solve this in O(n) time using hasing ( but you would also be using O(n) memory.)the basic idea:1. put all elements in the list into a hashset (or hashmap)2. for each element in the list, check to see if (value – element) is in the hashset. if it is, then those elements add to value.ie.def findPairs( list, value ): ret = [ ] hm = {} #new hashmap for elem in list: hm[elem] = True for elem in list: if (value – elem) in hm: ret.append( (value, value – elem) ) return ret |
question :
There is a special linked list where each node have two pointers, one pointer for next node and one pointer for randomly chosen node. Create a deep copy of this list. |
answer:
This post has been removed. Please see our |
answer: Here’s an answer (in C#):static LinkedList<Node> Copy(LinkedList<Node> source){ Dictionary<Node, Node> map = new Dictionary<Node, Node>(source.Count * 2); LinkedList<Node> copy = new LinkedList<Node>(); foreach(Node x in source) { var clone = (Node)x.Clone(); copy.AddLast(clone); map.Add (x, clone); } foreach(Node x in copy) { x.RandomLink = map[x.RandomLink]; } return copy;} |
question :
Find the least common ancestor of 3+ nodes, in a binary tree wher the nodes only point to their parents. No child pointers. |
answer: In this solution, I’ll try to present the general idea of a solution with psuedocode to help explain my answer. I apologize if the psuedocode is slightly buggy – I did not try it in a compiler. It is just to help show the overall idea.Algorithm – LCA1) Find the depth of each node in the input. Store in hashmap called DEPTH where DEPTH[node] = nodes depth. This can be done in O(lg(n) * input size)2) Compute the minDepth. (O(inp))3) The idea of this step is to find nodes that All have the same depth The following pseudocode is an idea of how this may be done. There are many different ways to do it. for node in inp: prev = node.copy while depth[node] != maxDepth: node = node.parent depth[node] = depth[prev] – 1 prev = node O(lg n * inp size)4) Find when all nodes in the inp list are equal. while not allNodesEqual(inp): for node in inp: node = node.parent O(lg n * inp size) 5) return inp[0].The overall runtime of this algorithm would be O(lg (n) * m) where m is the size of the input list |
answer: divide and conquer:finding common parent of a list of nodes =finding common parent of the first node in the list and the rest of the nodesnode* find_common_parent(node[] node_list, int num_nodes, node* a_node){ if (num_nodes == 0) return a_node->parent; return find_common_parent( node_list+1, num_nodes-1, node_list );} |
answer: sorry i did not think through in my last post. this is the correct ans (hope so), and may need optimizationbool is_ancestor(node* n, node* ans){ //make sure n != ans node* p = n; while ( p->parent != null ){ if ( ans == p->parent ){ return true; } p = p->parent; } return false;}node* common_ances_on2(node* n1, node* n2){ if (n1 == n2) return n1; if is_ancestor(n1, n2) return n2; if is_ancestor(n2, n1) return n1; return common_parent_on2(n1->parent, n2->parent);}node* common_ances(node[] ls, int len){ node* ls_hdr = ls; if (len == 1) return ls; if (len == 2) return common_ances_on2( ls_hdr, ls_hdr+1 ); node* cm_ances = common_ances( ls+1, len-1 ); return common_ances_on2( ls_hdr, cm_ances );} |
question :
Describe Hash Tables |
answer: A hash table is simply a data collection that allows the programmer to store values using look up keys. It’s basically the same thing as a associative array. |
answer: I would also try mentioning something about collisions and the different methods for handling them. |
question :
You have a file of 1 million numbers, how do you find the top 1000? |
answer: This question is a bit tricky because it could mean several different things. Top 1,000 could mean "highest" or it could mean first 1,000 numbers stored in the top of the file.I would store the numbers in an array and perform a quick sort to retrieve the "highest" but if it were the top "first" 1,000 numbers i would store the first 1,000 numbers beginning at the start of the file in an array and return the array. |
answer: Since there are million numbers, interviewer has already given hint that you cannot load all of the numbers in memory – so Jason’s solution is not welcome.The other way might be: load portion of file-data in chunk and do merge sort.Then do a n-way merge and pickup the first 1000 numbers. |
answer: Just put them in a heap and keep the heap trimmed. O(n) because inserting in the heap is constant O(log(1000)). |
question :
Write an algorithm to see if a tree is a BST. |
answer: isBST(Node root) if root == null return false return isBST(root, root.value, true) && isBST(root, root.value, false)isBST(Node root, Int root_value, Boolean left) if root == null return true if left == false ? rot.value <= root_value : root.value >= root_value && (root.left == null || root.left.value <= root.value) && (root.right == null || root.value < root.right.value) return true && isBST(root.left, root_value, left) && isBST(root.right, root_value, left) return false |
answer: It is as if the simple solution above didn’t detect correctly following case: 2 1 3 0. 4 |
answer: isBST(Node node): if node == null: // no node is technically a bst tree return true; if node.left != null: if node.value < node.left: return false; if node.right != null: if node.value > node.right: return false; return isBST(node.left) && isBST(node.right);test:isBST(tree.root) |
answer: The above wont work, consider a tree that has a root value for 5, left is 4, right is 6, left of the left is 3 and right of the left is 6. This one should work (for integers):boolean isBST(Node root) { return isBST_helper(root, INT_MIN, INT_MAX);}boolean isBST_helper(Node root, int min, int max) { if (root == null) return true; return root.value >= min && root.value < max && isBST(root.left, min, root.value) && isBST(root.right, root.value+1, max);} |
answer: public boolean checkBst(Node n) { if (n == null) return true; if (checkBst(n.left)) { if ( checkBst(n.right)) { boolean isBst = false; if (n.left != null){ isBst = n.left.data < n.data; } if (n.right != null){ isBst = n.right.data > n.data; } return isBst; } } return false;} |
answer: A mistake below corrected..public boolean checkBst(Node n) { if (n == null) return true; if (checkBst(n.left)) { if ( checkBst(n.right)) { boolean isBst = true; if (n.left != null){ isBst = n.left.data < n.data; } if (n.right != null){ isBst = n.right.data > n.data; } return isBst; } } return false;} |
answer: What Jordan is saying is correct. We need to maintain bound for left and right subtrees.The bound for left is min and root.value and for right is root.value and max. The above give n by me in incorrect. The correct on lines of Jordan – public static boolean isBST(Node t, int min, int max) { if (t == null) { return true; } if (isBST(t.left, min, t.value) && isBST(t.right, t.value, max)) { boolean bst = true; if (t.left != null) { bst = (t.left.value >= min) && (t.left.value <= max); } if (t.right != null) { bst = (t.right.value >= min) && (t.right.value <= max); } return bst; } else{ return false; } } |
question :
find the closest pair of points in a 2 dimensional space.? write an algorithm. |
answer: Answer to your question."1) How would you find a number which is repeated odd number of times in array of number where every other number is repeated even no of times.?"Soln:1) Use XOR operation2) for example, 1 ^ 1 =0. So if any number is repeated even number of times it is zero.3) If a number is repeated odd number of times say 3 times then a) 3^3 =0 b)0^3=3.int XOR=array[0]for(int i=1;i<array.length;i++){ XOR=XOR ^ array[i]} |
answer: find the closest pair of points in a 2 dimensional space.? write an algorithm.?This is typical computational geometry. To find a closest point, use the pigeon hole principle and this will bring down computational time to O(n* logn). |
question :
typically questions consist of book defination of class and object, polymorphism , over riding etc |
answer: They are interested in knowing whether you know well enough what is class and what is object. Try to give real life example |
answer: A class is the blueprint from which individual objects are created. For example there might be a class for chairs and every chair created from this class is an object. Every chair object is unique.polymorphism – one interface can be implemented in several ways. For example a list can be implemented using an array or using linked objects.overriding – a method in the subclass with the same signature overrides the method in the super class. |
question :
write a function to find 2nd highest value in an array. Basic questions on STL library , some baisc regrex questions , difference between left join right join ( only basic stuff). I guess w3school tutorial is fine incase if you want to refresh . simple sql query using joins. |
answer: For sql , w3schools tutorial is enough to brush up the things |
answer: Second highest number in an arraypublic class SecondHighest { public static int secondhighest(int[] arr){ if (arr == null){ return -1; } if (arr.length ==1){ return -1; } int max = arr[0] > arr[1] ? arr[0] : arr[1]; int max2 = arr[0] <= arr[1] ? arr[0] : arr[1]; for (int i=2; i<arr.length; ++i){ if (arr[i] > max){ max2 = max; max = arr[i]; } else if (arr[i] > max2){ max2 = arr[i]; } } return max2; } public static void main (String[] args){ int[] arr = {1,-2,4,7,-9,45,34,-92}; System.out.println(secondhighest(arr)); }} |
question :
Given a 5×5 board containing random characters, find all words that can be formed from consecutive adjacent (diagonals count) characters. |
answer: I tried using depth-first search with recursive backtracking. I explained my reasoning but couldn’t formulate a good implementation. |
answer: def puzzle_solver(puzzle, dictionary): root = puzzle.start() # some arbitrary starting point letter solutions = {} explored = {} stack = Stack() stack.push( [ root ] ) while not stack.empty(): node = stack.pop() # this is a list of letters/states in the gameboard if node in dictionary: # if the thing we just popped off is actually a word solutions.add(node) explored.add(node) # prevent re-visiting states we’ve previously visited for c in neighbors(node[-1]) # adjacent letters if node + [ c ] not in explored: stack.push(node + [ c ]) explored.add(node + [ c ])Inefficient, but easy to explain answer |
question :
If you are 1 month behind on the 3 month project how would you deal with the stakeholders? what would you do?…Further questions about dependant teams and whatnot stemming from the answer. |
answer: Give them a choice reduce scope, more resources, change deadline. |
answer: I would evaluate & summarize the problems that caused the delay, identify if any of these were already identified as risks in the project plan, and meet with the team to discuss how to deal with the delay. I would also re-evaluate project risks & develop plans to identify these new risks as early as possible (fail fast approach). I would then meet with stakeholders to discuss the state of the project, get their input, and possibly present group-derived solutions if they align with the stakeholders desires. Alternatively, I would set up a follow up meeting once I’ve met with the group to discuss the feedback from the stakeholders & generated alternatives. |
question :
Give a 2D rectangular array represented as a 1D arrary in row-major form, rotate the array by 90 degrees |
answer: I came up with a solution where you transpose the array and then exchange the colums. But this is very inefficient. Does anyone have a better solution. |
answer: Let n be the number of rows and m be the number of columns. Make m stacks of (n-1) size, |
answer: Let n be the number of rows and m be the number of columns. Make m stacks of (n-1) size and iterate through your "2D" array by successively pushing entries through stacks: eg. (entry i is being pushed in stack ~(i mod m)) when i reaches m x (n-1) pop stack and overwrite entries in the "2D" array from the beginning until empty + i’th entry then go to the next stack. Repeat until done. this should run in m x (n-1) + m x n = m x (2n +1) and uses m x (n-1) x (data entry mem size) extra memory during the run. If you want to use less memory, it gets a whole lot more complicated but won’t be as quick. |
answer: C uses row-major order to lay out arrays in linear order. So:int orig[2][5] = { {0,1,2,3,4}, {5,6,7,8,9} };is this in memory:0,1,2,3,4,5,6,7,8,9Assuming clockwise rotation, I think we want to transform:5678901234into:9483726150which is equivalent to a transpose then a mirror about col==nrows.Assuming this is so:#include <stdio.h>const int nrows = 2;const int ncols = 5;int orig[2][5] = { {0,1,2,3,4}, {5,6,7,8,9} };int final[5][2];void main(){ int row, col; for(row=0;row<nrows;row++) { for(col=0;col<ncols;col++) { // equivalent to transpose then mirror about col==nrows final[col][nrows-1-row] = orig[row][col]; } } for(row=0;row<ncols;row++) { printf("\n"); for(col=0;col<nrows;col++) { printf("%d ", final[row][col]); } }}this would be O(rc), where r = #rows, c = #cols. Quick enough i suspect. |
question :
Rand(7) from Rand(5) |
answer: The simple solution is to implement RandBin() using Rand5().int RandBin(){} |
answer: Sorry this UI posts without warningint RandBin(){ int rand5Res = Rand5(); return rand5Res < 2 ? 0 : rand5Res < 4 ? 1 : RandBin();}And then use RandBin() to implement Rand7;int Rand7(){ int rand = RandBin() << 2 | RandBin() << 1 | RandBin(); return rand < 7 ? rand : Rand7();} |
answer: int rand7(){ while(1) { int n = ((rand5()%2)*4 + (rand5()%2)*2 + (rand5()%2)*1); if(n == 0) continue; return n; }}The rand5()%2 will generate 0 and 1 with equal probability and we need 3 bits since we are going from 000 upto 111. So we call this function thrice for each bit position. |
answer: Above answer is not correct because 0 is not returned. We need equal probability for all 0, 1,2,3,4,5,6. The modified would be:int rand7(){ while(1) { int n = ((rand5()%2)*4 + (rand5()%2)*2 + (rand5()%2)*1; if(n==0) continue; return n-1; }} |
answer: Java:Random r = new Random();r.nextInt(5)+r.nextInt(5)%3 |
answer: what about calling rand(5) 7 times adding it then % 7( rand5() + rand5() + rand 5() + rand5() + rand5 () + rand5() + rand5() ) % 7-suhane |
question :
1. Find out that data in a linked list is a palindrome |
answer: Put all the values in the linklist into a hashmap with each spot equal to its location on the linked listthen using two pointers, one at 1 and the other at size of the link listcompare the values at both pointersif equal, add one to the smaller one and remove one from the othercompare the values at both pointersdo until both pointer value are the same or values at the pointer are not equal. |
answer: 1) Traverse the linked list .put the nodes on the stack.2) Traverse the linked list second time and pop the node from stack.Compare them. if equal repeat 2 until stack is empty else linked list is not palindrome. |
answer: I would try to see what type of linked list it is. If singly, the stack method would work well. For doubly, traverse to the end of the list and compare it to the front. Traverse inwards until left node equals the right node. |
question :
2. You have an array (size is not known) and whose elements are having the values from 0-> 99. Find out the three largest elements in that array and return those. |
answer: Could be solved using a max-heap if the value kept is larger.In this case keep track of an array with three largest numbers;int n=3;int i=0;int* maxNum= new int[n];while (arr[i]){ if (arr[i]>maxNum[n-1]) { maxNum[n-1] = arr[i]; sort(arr); } if (maxNum[n-1] == 100-n) break; // Max number would not change any more i++;}not sure if there are more efficient method given the fact that all numbers are within 0->99 |
answer: I may be wrong but here is my ideaWe first find the largest value and push it on to a stack.we find the second largest value by comparing the [i]th value to [i+1]th value while being lesser than the stack (top) value–until the end of the unspecified size of the array— thats the second largest.And then we find the third largest by doing the same by comparing the current to the next integer value in the array while being less than the stack (top) which will give us the third largest.void find3largest (A[ ]){int a,b,c=0;stack s;for ( i=0;i<=n;i++){if ( A [i]>A[i+1]){a=A[i];}s.push(a);//* largest value in the array*//for (i=0;i<=n;i++){ if ((A[i]>A[i+1])&&(A[i]<s.top()))b=A[i];}s.push(b);repeat the same thing for c.Print the stack and the 3 largest should be present thereNow this solution is probably quite costly – and I am sure the heapsort mechanism provided above is the most efficient way to go about it– this is just a layman’s code |
answer: Use counting sort. Just pick the last 3 elements in the sorted array.Or why not just traverse the array 3 times??? Since the question doesn’t specify an upper bound of the comparison times. |
answer: Just keep three variables, max1, max2, max3 and every time you find a number larger than the smallest, throw away max3 and sort max1, max2 and max3 |
question :
Implement atoi |
answer: int myatoi(char *string) { int val = 0; if (string) { // Error checking to eliminate NULL string while (*string && *string <= ‘9’ && *string >= ‘0’) { val = (val * 10) + (*string – ‘0’); string++; if (*string != ‘\0′ && !(*string <= ‘9’ && *string >= ‘0’)) return 0; // Error checking to eliminate cases like ’12ABC34′ } } return val;} |
answer: atoi also handles the case when there is a leading plus or minus in the string. Also it doesnt go to the end of the string. Just till the first white space character in the string |
answer: int my_atoi(char *str){ int ret = 0,sign=1; if(*str == ‘-‘) { sign = -1; str++; } while(*str) { ret = (ret * 10) + (*str – ‘0’); str++; } return ret*sign;} |
question :
This was not unexpected but a bit difficult. How would you represent the ordering of a deck of card if you only have 32bytes to work with. So, he explained that you have 52 objects, there are 52! possible ordering of them. how to encode one of those ordering within 32 bytes? |
answer: have to come up with a numbering scheme for each permutation |
answer: After encoding the first 20 cards, reindex the remainder and use 5 bits for every card instead of 6. Repeat that.(20*6 + 16*5 + 8*4 + 4*3 + 2*2 + 1) = 249 bits32 bytes is 256 bits. |
answer: Evert: your solution is good, but can be improved even a little further by starting the encoding with just 1 bit:1 bit -> encode 1 card2 bits -> encode 4 cards3 bits -> encode 8 cards4 bits -> encode 16 cards5 bits -> encode 25 cards1 * 1 + 2 * 4 + 3 * 8 + 4 * 16 + 5 * 25 = 222 bits |
answer: @Tester : i dont think you can start with 5 bit code, first indexing has to be 6 bit.@evert: yours should work!although the implementation would be a little slow. But with this problem you can achieve the theoretical minimum log_2{52!} (that is the information content of the message passed) by numbering each permutation. That is order (preferably lexicographically) each permutation. And number then incrementally. |
answer: @evert, could you please give more detail on how to convert 32 bytes to 52 cards?Isn’t there any conflict with the encodings?Thanks |
answer: huffman coding, I guess |
answer: nope, not huffman, there is no frequency variation. everything appears once. |
answer: This problem can be handled by using 4 bits for each face card and 2 bits for the suit.We will use (4*13) for each face card and (2 *4) for the suits.Combined this would consume 52 for an entire deck of card.struct Card { unsigned char face:4, suit:2;}; |
answer: How about this:Don’t use any bits for the suit. Instead, use the implied position: first pair of 13, second pair of 13, etc.depict the suit. Then 3 bits for first seven faces and 3bits for the next six. Now let’s do the math (hold on, let me take out my calculator, got it):7 x 3 + 6 x 3 = 39. Then 39 x 4 = 156 bits or 19 bytes. |
question :
count the number of times a word has occurred in a given string |
answer: Scan the input string and look for ‘words’ (separated by spaces).. as you find each word, check with the test word, if same increase count by 1. Do this until the end of input string. |
answer: #include <stdio.h>#include <stdlib.h>char* substr(char* input, int start, int end){ char* output = (char*)malloc(100); if(!output) return; int i=0; while(start<=end) { output[i] = input[start]; start++; i++; } output[i] = ‘\0′; return output;}int FindWordCount(char *input, char* target){ int start=0, end = 0; int cnt = 0; while(input[end] != ‘\n’) { if(input[end] != ‘ ‘) { start = end; while(input[end] != ‘ ‘ && input[end] != ‘\n’) end++; //Come back to the last index of the valid word; end–; if(strcmp(substr(input, start, end), target) == 0) cnt++; } end++; } return cnt;}int main(){ char* input = " hello there how are you doing? Such a hello day there hello"; char* target = "hello"; printf("Number of occurances are %d", FindWordCount(input, target)); return 0;} |
answer:
This post has been removed. Please see our |
answer: Python code——————def main(): s_str = "hello there how are you doing?Such a hello day there Hello" s_str = s_str.lower() s_str = re.sub(‘[^A-Za-z]+’, ‘ ‘, s_str) l_str = s_str.split(‘ ‘) d_str = {} for s_word in l_str: d_str[s_word] = d_str.get(s_word, 0) + 1 print d_str |
question :
How would you implement a sparse array (key could be any integer, but only a few would be used) with limited memory. |
answer: A hash table.A linked list is possible but random access isn’t efficient |
answer: need to support efficient sequential read as well. b-tree |
answer: Assuming sparse means many values are zero:have 2 arrays: one to store non-zero indexes, the other to store the values at the non-zero index. If queried number is not in the index set, return 0. |
answer: Hash table |
question :
Matrix multiplication |
answer: This question is very basic and not worth saying anything |
answer: Strassen Algorithm, Divide and Conquer |
question :
find LCA for two nodes of a binary tree. |
answer: List 1: tree nodes inorderList 2: tree nodes postorderList 3: all the nodes in between the given 2 nodesList 4: all the nodes after the given 2 nodesthe LCA is the common node in List 3 and List 4. |
answer: I think there’s an easier solution:List1: the parents of node1 in order bottom to top (can get them by navigating up tree from node 1).Navigate up tree from node2. First parent of node 2 found in list1 is LCA. |
question :
how to merge two sorted linklist? |
answer: Use MergeSort. |
answer: You don’t need merge sort here. This is a O(n) task, because the lists are already sorted. In fact, this merge routine is part of merge sort. No sorting takes place here, only merging, and it could be done in linear time.Node* merge(Node* list1, Node* list2) { Node* merged = null; Node** tail = &merged; while (list1 && list2) { if (list1->data < list2->data) { *tail = list1; list1 = list1->next; } else { *tail = list2; list2 = list2->next; } tail = &((*tail)->next); } *tail = list1 ? list1 : list2; return merged;} |
question :
Write a function that takes a BinaryTree and validates if it is a valid BinarySearchTree. Assume the tree contains no duplicate values. |
answer: Write a recursive function that take the node as input and return three values:1, If the tree rooted with this node is BST or not,2, the max/min of the tree rooted with this node.If the node has children, the tree rooted with this node is a BST if:1, Both its left and right children are BST2, Max value of left < node < min value of rightIf the node has no childres, return (tree, node value, node value) |
answer: Do an inorder traversal and check if the elements are sorted. |
question :
Code to get the depth of a binary tree. |
answer: should be easy if you have done it before. |
answer: int depth(node * root) {if (root == null) return 0;return max(depth(root->left), depth(root->right) + 1;} |
question :
sort large amount of records saved in several files. |
answer: need to consider memory problem. |
answer: When you can’t fit everything into memory, just use a merge. Sort each of the small files. Look at the first element of each small file, pick the smallest and write it out to the output file. Repeat until there are no more elements. |
question :
Given two numbers n and m, divide n by m without using the division operator. Return both the integer answer as well as the remainder. |
answer: I first assumed that both numbers were positive and then used repeated subtraction to come up with the answer. Upon further discussion I felt that this took too long and tried to come up with some kind of faster method to accomplish this but I could not design it in the time required. Thinking about it there are some other choices:1) Treat the numbers as binary and then use shifting and subtraction to divide. I can’t really solve this easily.2) Calculate …, 16m, 8m, 4m, 2m, 1m, etc. and the subtract each of those from n if possible. If you can subtract it shift the answer and add a 1.Finally, compare the signs of n and m to set the signs of the answer. |
answer: n * m ^(-1) |
question :
1. Given a depth d, build a complete tree of depth d. 2. How would you test it? 3. Why did you select your particular solution approach? 4. What level of programmer could be expected to code this? |
answer: 1. I built a recursive function that created a node and then called the same function recursively for left and right subnodes and depth d – 1.2. I tested some use cases (including d < 0, d = 0, d = 1 and d > 1)3. I picked recursion because tree algorithms naturally lend themselves to recursion because tree problems generally build on smaller subproblems4. I said junior programmer though they sometimes struggle with testing edge cases. |
answer: void build_tree (int d, node n) {if (d != 0) { node n_right = new node(); node n_left = new node(); n.right = n_right; n.left = n_left; build_tree (d-1,n.left); build_tree (d-1,n.right);}} |
question :
Provide test data for a program whose functionality is to find second smallest number in a set |
answer: 1 2 3 2 2 2 4 5 6 2 2 1.9 2.1 |
answer: give only number as input |
question :
Check given binary tree is BST or not |
answer: The left subtree of a node contains only nodes with keys less than the node’s key.The right subtree of a node contains only nodes with keys greater than the node’s key.Both the left and right subtrees must also be binary search trees. |
answer: Just do Inorder traversal and make sure that the numbers are printed in increasing order assuming that the key is integer! Looking back, inorder traversal prints BST in ascending order. |
question :
How would you sort a 32 GB file with a number on each line. |
answer: External sorting ?Using merge sort on each chunk. Decide chunk based on memory available |
answer: Bubble Sort would work but it’s pretty slow.Shell Sort is also O(1) space complexityComb Sort works too; it’s a modification of Bubble Sort that rivals QuickSort in terms of average time |
question :
Come up with a formula to calculate the angle between the hour hand and the minute hand in a clock. |
answer: mod( (hour-(min/5))*30) |
answer: 6(min mod 5 + 5*Hour – min) |
answer: 6(mins between hands)=angle |
question :
Write algorithm/code to find longest path between any two cities. 4X4 matrix was given. If there is no connectivity between two cities then the distance between them was given as -1. Its cyclic graph. |
answer:
This post has been removed. Please see our |
answer: Finding longest path between two nodes in a graph is an NP Hard problem. So, we should not try to find a polynomial solution to this problem.As you can see the given problem is of very small size. So even brute force is acceptable.Solution:Let there be n cities. GIven starting city as S and destination city as D. We are left with n-2 cities.There are approximately 2^(n-2) * (n-2)! ways for reaching D from S.Find length of all these ways and choose the smallest one. |
question :
Given 2 files, each line in the files is considered an entry. Print the entries that are duplicated in both files such that the number of repeated entries are minumal. Example: File 1: aaa aaa bbb bbb bbb ccc File 2: aaa aaa aaa bbb bbb result: aaa aaa bbb bbb |
answer: Use a hash table. Read each line form file 1 and use the entry as key and store 1 as value, if entry already exists add 1 to the value.Read file 2 and check hash table, if entry found and value is >= 1 print the entry and subtract 1 from the value. |
answer: There are 2 cases to be considered in this question.Case 1: [Easy]The size of the 2 files are not large i.e. the data can be fin in RAM. In this case you can read both the files completely and store them in a data structure like hash table, array etc. You can apply your algorithm and write the output in a file.Case 2: [Tricky]Files are very large and cannot be read and put in main memory.——————————————————————————————Exp : RAM is 2 MB and file size is 5MB each.In this case you have to accomplish the task part by part.My Solution:Steps:1. Copy data of file 2 at the end of file one.2. Apply External Sort (http://en.wikipedia.org/wiki/External_sorting)3. Print the data in output file while removing the duplicate data. |
answer: Print_it(){ Static File file1; Static File file2; Static Str1 = file1.read();Static Str2 = file2.read();Str = str1; While(str1.equals(str2) || )Print str If (str1.equals(EOF)) exit;While(str.equals(str1)) Str1++; If (str1.equals(EOF)) exit;While(str.equals(str2)) Str2++; If (str1.equals(EOF) || str2.equals(EOF)) exit; Print_it();} |
question :
convert binary tree to double linked list |
answer: I’m going through that process right now. Hopefully in between the phone screens and onsite interview but I may well just be at the end of the road with Amazon. I’ll find out I suppose. I didn’t get anything close to this question though. But here’s my shot.If you need to use the same nodes and keep them in order, you might consider right and left to be prev and next and make the binary search tree no longer a binary search tree and instead a doubly linked list.std::pair<node *, node *> flatten_and_return_ends(node *root_node){ node *first, *last; if (root_node->left) { std::pair<node *, node*> left_minmax = flatten_and_return_ends(root_node->left); first = left_minmax.first; left_minmax.second->right = root_node; root_node->left = left_minmax.second; } else first = root_node; if (root_node->right) { std::pair<node *, node*> right_minmax = flatten_and_return_ends(root_node->right); root_node->right = right_minmax.first; right_minmax.first->left = root_node; last = right_minmax.second; } else last = root_node; return std::pair<node *, node*>(first, last);}on the other hand, if they just want you to push the nodes in order into a listtemplate<class _NodeValueType>void add_to_list(node *root_node, list<_NodeValueType> &values){ if (root_node->left) add_to_list(root_node->left, values); values.push_back(root_node->value); if (root_node->right) add_to_list(root_node->right, values);}I didn’t check for validity so there may be typos |
answer: Check out this in place DoublyLinked Conversion of Tree.1. Link a Node to its leftchild’s rightchild as its leftchild.2. Make Node as right child of original leftchild.3. Apply recursion.Node fn = null ; //First NodeNode ln = null ; // Last Nodepublic Node asDoublyLinkedList(Node root){ Node parent = root; Node current = root.leftNode; while(true){ if(current==null) { if(fn==null) fn = parent; if(parent.rightNode==null){ ln = parent; return parent; } Node n = asDoublyLinkedList(parent.rightNode); parent.rightNode = n; n.leftNode = parent; if(ln!=null){ ln.rightNode = fn; fn.leftNode = ln; } return parent; } parent.leftNode = current.rightNode; current.rightNode = parent; parent = current; current = parent.leftNode; } } |
answer: Do inorder traversalPass char **root as the second argument to the traversal function along with whatever argument you to pass to the functionAs part of processing, instead of displaying the content of the node, store the node in the second argument root, if root is not already NULL. Else store the current node as the right most node by iterating through the linked list where root is the starting node. |
question :
You have two very huge arrays of integers, they have only one element that is different. How do you find the different one? |
answer: Add up first n elements of both arrays and compare the sums. Now add next n and compare. Keep repeating until you find a index range for which sums are different.Now repeat the same on new subarray with n = n/2 and so on until n = 1. |
answer: Solution by Gaurav Agarwal is valid only if both arrays are sorted. |
question :
Given an array of integers and another integer X – create an algorithm to determine if the sum of any two integers in the array would result in x |
answer: hash table keyvalue x-arr[i] |
answer: iterate and store in a HashTable <a[i],x-a[i]> . now loop again and see if any number matches the difference i.e x-a[i].Complexity should be O(n)+O(n) ~ O(N) |
question :
design a ADT to implement push(), pop() method as stack, and also has a getMinElement(). Require that getMinElement() is constant time but push()/pop() do not have to be constant time at first. Then for improvement, these three methods are all required to be constant time |
answer: For the first half, a minheap is enough. For the second half, use two stacks, the second stack store the min value. |
answer: second part isn’t theoretically possible .. sounds like the question was mis quoted.Say you have a trillion numbers. You can’t push a random number to that list of numbers in constant time and still be able to always get the minValue .. at a minimum you need to do logN insert into a minheap. |
answer: well, ok, I suppose you might be able to do something if you knew the range of numers before hand. that’s not exactly ADT though. |
answer: even then, it would be o(range of numbers) .. that’s not exactly constant time given that integers can get rather large. Often larger than the actually length of the stack you’re popping/pushing from. |
answer: also a minheap isn’t enough for the first part. minheap doesn’t retain fifo you need for stack. |
answer: Having a push and pop done in constant time strongly implies a linked list structure. The getMinElement seems like a red herring to get you thinking minheap. In reality if it’s just a linked list you can easily keep a pointer to the node that currently has the lowest value element (or the prior node if getMinElement implies removal from the linked list). |
question :
If a stick breaks randomly in three pieces, what is the probability that you can form a triangle from the pieces. |
answer: Assume a uniform probability distribution across the entire stick for each break.Remember a triangle can only be formed if the sum of the lengths of any two sides is greater than the remaining side. Now, assume the sick length is one and assign X, Y and 1-X-Y to be the side lengths. Next, create three inequalities based on the requirement for a triangle and simplify. Next, plot the values X and Y can take when unconstrained by the need to form a triangle. This gives you the triangle [(1,0)(0,0)(0,1)]. Next, plot the constrained X and Y values giving another triangle [(.5,0)(0,0)(0,.5). Notice that the constrained triangle has a fourth the area of the unconstrained triangle. So, the probability you can form a triangle is .25. |
answer: that looks wrong to me. why not just list the possible outcomes evenly and circle the ones that look viable for a triangle. I think you’ll find that list is greater than 1/4. |
answer: say the length of the stick is l; first break at location x then y.All you need to make sure is if x<l/2, y>x OR x>l/2, y<xusing a probability integration of dx from 0 to lMy answer is 3/4 |
answer: There are many ways to solve this problem. But, the answer is 1/4. Google it. |
answer: A triangle is possible if the biggest piece < 1/2 of the original length.1. First breakpoint can be anywhere. P=12. 2nd break should be in the larger piece. P=1/2So answer should be 0.5 |
question :
Write a function to print first n odd powers of 3, where n is given. |
answer: void power(int n){ if (n<=0) throw illegalargumentException else { for(i-1;i<=n;i++) { int result = Math.pow(3, 2i-1); System.out.println(result); }} |
answer: void power(int n){ if (n<=0) throw illegalargumentException(); else { int result = 3; for(int i = 1; i< n; i++) { System.out.println(result); result *= 9; }} |
question :
the second question was a little tougher, "Write a function that checks whether a binary tree is valid or not. A valid binary tree is a tree where no child node points to any of its ancestors" |
answer: Use BFS with a queue, for each new element q[n] n is even check if q[n/2] is pointing to the same element. |
answer: On second thought, DFS should be used.This is to imitate a linked list loop detection situation. So we have to make sure that every time we check we have to make sure that all the elements should be in the same line. |
question :
Reverse a line with all word reverese as well.. Like i am Dhar to raha ma i ekil |
answer: use a stack and throw everything there and then pop out each one to get in reverse order |
answer: Take 2 pointers, first and last.Then just swap every char (including spaces) till first <= last. |
question :
least common ancestor |
answer: it is a binary tree question |
answer: Traverse down the tree as you would if you were searching the two elements normally. Eventually you will encounter a split decision where you want to do two out of these three possible actions (1) stay at node (i.e., found one of the values), (2) go left, (3) go right. This node is your answer.Assumption is that the tree contains both values. |
answer: @Anonymous: that works only if it is a BST |
question :
Find the numbers occur odd times (e.g. 1,3,5,7,…) in the given array. e.g. { 2, 2, 1, 1, 1, 4, 4 } You should print 1. |
answer: I solve the problem, but it was not an optimal way. I didn’t have enough time to solve it nicely. |
answer: The optimal way would be to XOR everything together. Only the element appearing odd # of times would remain |
answer: For each array element, store it in a set except that if it’s already in the set then remove from set. At the end of the array, this set will contain only elements that are odd. This algorithm is O(n) and visits each element only once in the array at an extra cost of memory for the set.This can be done in constant memory by first sorting the array and then iterating thru the elements counting each number and printing odd numbered ones. However, this algorithm is O(n log n) for the sort + O(n) for the final iteration, trading time for memory. |
answer: Use a Hash Table/Mapfor each element in the array add it to the table if its not in the table, else remove it if it is.Once you are done iterate the hash and output the values |
question :
Find the largest palindrome in a given word. |
answer: Assume a single character is a palindrome of size 1. To begin, iterate starting at the beginning of the list. If element[i-1] == element[i+1], then continue continue checking with 1 replaced with 2, and so forth. Eventually you’ll arrive at a contradiction; set currentBest accordingly. Continue to end of list, replacing currentBest as needed.One optimization, if (currentMax/2 > arrayLength – i) then stop searching; It is impossible to find a longer palindrome with the remaining portion of the list. |
answer: Good old Suffix tree. |
question :
Given a linked list, flip every pair of nodes, such that if given a-b-c-d-e, return b-a-d-c-e. |
answer: void flipEveryPairLinkedList(Node *n){ value t; while (n != null && n.next != null){ t = n.value; n.value = n.next.value; n.next.value = t; n = n.next.next; }} |
answer: A recursive version, in Python:def flipRecur(node): next = node.next if(next == None): # 1 element list return node next2 = next.next # None.next == exception if(next2 == None): # 2 element list next.next = node node.next = None return next next.next = node node.next = flipRecur(next2) return next |
question :
Implement atoi() |
answer: #include <string>#include <math.h>int myAtoi(string str){ int result = 0; string numStr = ""; for (int i = 0; i < str.length(); i++) { if (str[i] >= ‘0’ && str[i] <= ‘9’) { numStr += str[i]; } else { break; } } if (numStr.length() > 0) { for (int i = 0; i < numStr.length(); i++) { result += (numStr[i] – ‘0’) * (int)pow(10.0, (int)numStr.length() – 1 – i); } } return result;} |
answer: Dan’s answer doesn’t handle negative numbers — make sure to specify if it needs to handle it! |
question :
Implement clearbit(int n, int p) function, p is the position of the bit to be cleared. Example : n is 13, p is 0. Binary representation of n : 1101. You need to clear the pth postion, means 0th position bit needs to be cleared. |
answer: Pretty trivial–just shift 1 the correct number of places (based on p) and XOR this with the integer n. |
answer: You’re wrong, as always. |
answer: #include <math.h>#include <limits.h>int clearbit(int n, int p){ return n & (INT_MAX – (int)pow(2.0, p));} |
answer: get the pth position bit to 0th position by shift operations to get some number say n.& n with (n-1). that clears the last bit, which was pth before shifting. |
answer: get the pth position bit to 0th position by shift operations to get some number say n.& n with (n-1). that clears the last bit, which was pth before shifting. |
answer: int clearbit(int n, int p){return (n & (~(1 << p))); /*assuming that p<8*sizeof(int) */} |
question :
Math Question: Inbound Flow Question: You are in charge of the department that receives the product in to the building and stows it to the bin where it is accessible by the department. you have two options on how to receive and stow the product. In the first option, you receive the product at 250 units per labor hour and stow it at 100 units per labor hour. You must receive it and stow it for the unit to count for production. This process results in 1% of the units stowed being incorrect. You can find and fix these errors at a rate of 20 units for labor hour with what you believe is almost 100% accuracy. In the second option, you receive and stow the product in one step vs. two. The rate for this process is 80 units per labor hours for receive and stow. This process results in 1.5% of the units being stowed being incorrect. You can find and fix these errors at a rate of 20 units per hour with what you believe is almost 100% accuracy. 1. Which option would you select to process today’s units and why? 2. Does your answer change if you are told you must fully process 100,000 units today? If yes, why? 3. Does your answer change if you are told that you have 15 associates today and you must fully produce the maximum amount of units possible? If yes, why? |
answer: Receiving and Stowing at a rate of 250units/3.5 labor hours ~71uph. Keeping up with the errors requires .0355 laborers. 71/1.0355 ~68.5uph.80units/hour produces 1.2errors/hour. this requires .06 workers. 80/1.06~75.47Method A allows 68.5uphMethod B allows 75.47uphAlways use B! |
answer: What I did was the following:Compare production if I had 10 people working on each project. It could have been 10 or 4 or 1,085 as long as they were equal.Option 1 at 10 people: 3 people to receive and 7 to stow helped to do 750 units/hr receiving and 700 units/hr stowing. Therefore production is really 700 with 50 that still needed to be stowed at .5 labor hour.Option 1 error rate at 700 units was 70. That takes 3.5 labor hours to correctOption 2 at 10 people = 800 units per hour received and stowedOption 2 error rate at 800 was 120. That takes 6 labor hours to correct.Option 2 looks better because at 10 people, if I used 9 to do the receiving/stowing I would still produce 720 and would have 1 person to correct all errors during the same shift with some time left over.For Option 1 if I went 3 people to receive (750) and 6 to stow (600) and 1 to correct errors (3.5 hrs) and stow (4.5 hrs) 55 units I’d still have some excess to stow.I can’t figure out the exact equation, but Option 2 definitely looks better. I think most organizations want managers who can figure out the best, if not most precise, solution. Then, they want the manager to get back to work to take care of people.Also, people aren’t fractions. You can fractionate their days by giving them different tasks but I think you have to take a pragmatic approach to creating a real solution.I chose Option 2 and I don’t think it matters whether there were 100,000 units required or 1,000,000. The equation is still going to be less efficient during Option 1 because of the requirement to receive and stow separately. |
question :
Given a list of n elements…every element has a duplicate except one…Find that lone number? |
answer: I think the best method is to create a hash table with all entries.. this is an O(n) operation.hash_map <int,int>.. i.e key and frequency of occurrence…so creating the map is O(n) and then searching for the element with frequency=1 is again O(n). Thus summing up to O(2n) which is nothing but O(n) time complexity.What was your response to this?? Any other ideas? |
answer: Create a temporary variable k = 0. Loop through the array bitwise XORing array elements with k. Since XOR is commutative and associative, the total will be the single element XORed with all the other elements each XORed with its duplicate. All the duplicates cancel to zero, and the XOR of the single element with 0 is the single element. So return k. This is also O(n), but does not require the memory used by a hash table. |
answer: @tophatThats a pretty sweet approach. Just tried programming it. It works like a charm! :)#include<stdio.h>#include<conio.h>void main(){ int list[7]={1,2,3,4,1,3,2}; int k=0,i; for(i=0;i<7;i++) { k=k^list[i]; } printf("No duplicate: %d",k); getch();} |
answer: @TopHat : Dude this is a great solution!! |
answer: Very good solution ! |
question :
The input to a function is an array of n elements.Output of that function is also an array where each element is product of all elements in the input array except the one with same index. Input ::::: 1 2 3 4 Output ::::: 2*3*4 1*3*4 1*2*4 1*2*3 |
answer: Either run two loops nested and carry out operations ==> O(n^2)or multiply every element at first, which is O(n) and then divide each element by the product to find individual answers ==> O(n)Total time complexity => O(2n) ==> O(n) |
answer: @NotThatBad those are the two I could come up with.The only other advice I have to contribute give is try to keep memory usage low (pass arrays by reference, rewrite over old array, etc)… You of course would want to find out if the function edits the original array, or leaves it in tact. |
answer: Create the Output array such that the value in every position ‘i’ is n! / i. The time complexity will be O(n) |
question :
You are given 1000 containers of water with exactly one container containing poison. You can use pigs to test which container contains poison. The conditions are that: A pig drinking the poisoned water woudl die exactly after 1 hour and that a pig could be used for sampling multiple containers. Assume that the pig takes 0 time to drink water from any number of containers. What is the minimum number of pigs would you use to identify the poisoned container within 1 hour. |
answer: 10 pigs (2^10 = 1024)This problem can be viewed as a mapping between bits and container.i.e0000000000 -> Container 1 (No pig drinks from this container)0000000001 -> Container 2 (Pig 1 drinks)0000000010 -> Container 3 (Pig 2 Drinks)0000000011 -> Container 4 (Pigs 1 and 2 drinks from this container)0000000100 -> Container 5 (pig 3 drinks from this container)….Every container has a unique combination of pigs that sample it. Therefore just examining which combinationof pigs die, one can infer which container holds the poison. |
answer: This is an application of the so called Hamming Code for error detection and/or correction. |
answer: really didnt get this one people. why would i spend 1024 pigs when i can just use 1000 pigs each drinking one container??? please correct me if i am wrong… |
answer: See the first answer – only 10 pigs are needed following a binary pattern of which pigs drink from which container. |
question :
How would you test if a binary tree were symmetrical and balanced. |
answer: Recursion, test if left->right equal to right->left, for example. |
answer: Could you please elaborate on your solution.I was thinking you can do an inorder traversal and then compare the result with 2 pointers starting from the extreme ends. Is that what you are suggesting ? |
answer: Well, the tree has to be balanced and symmetrical, so after the head node, the left must equal right on down.12 23 4 4 378 67 76 87I think my answer detected this, but he asked if I thought there were any problems with my answer and I couldn’t think of any, but he sure seemed to! |
answer: I don’t see any mention in your answer of checking whether it’s balanced. Is that what you were missing? |
question :
How do you check if a Binary Tree is a Binary Search Tree? |
answer: boolean isBST(Node root, int min, int max) { if (root == NULL) return true; if (root.value < min || root.value > max) return false; return isBST(root.left, min, root.value) && isBST(root.right, root.key, max);}/* first call would be isBST(root,INT_MIN,INT_MAX); */ |
answer: Or, perform an in-order traversal and see if the values are sorted |
question :
Amazon has to display the availability of an item even when it’s being viewed by millions of people. How would you design how this availability should be implemented so that it’s as accurate as possible while being updated as quickly as possible? |
answer: I said it should be put into memory but then he countered that there are many systems viewing the same item, with their own memories, how would one know if the last item is bought at another system? I really don’t know how to answer this question. |
answer: I also had the same question and my interviewer suggesting caching, and followed with a question on caching algorithms. |
answer: I suggest you read about eventual consistency in distributed system to get an idea about how these problems are solved |
question :
Find depth of a binary tree |
answer: using recursion |
answer: int depth(node * root){ if(!root){ return 0; } else { return 1 + max(depth(node->right), depth(node->left)); }} |
answer: @ajs: don’t forget the case of the root being the only node in the tree. If the tree consists of only the root node, then the depth should return 0.There needs to be an else if in there checking for this case, or else your function will return a depth of 1, when it should return 0:if (root.left == null && root.right == null) return 0; |
question :
Reverse a linked list |
answer: Maintain two/three pointer , pointer to the remaning list while one is being reversed, and then loop till the end |
answer: Node * reverse( Node * ptr , Node * previous){ Node * temp; if(ptr->next == NULL) { ptr->next = previous; return ptr; } else { temp = reverse(ptr->next, ptr); ptr->next = previous; return temp; }} |
answer: reverse without recursion:Node*reverse(Node *root){ Node* prev=NULL,*current=root; while(current){ tmp = current->next; current->next = prev; prev = current; current = tmp; }} |
question :
You have two sorted arrays – how can you effectively merge them into one giant sorted array? |
answer: Merge sort works using the principle that if you have two sorted lists, you can merge them together to form another sorted list. Consequently, sorting a large list can be thought of as a problem of sorting two smaller lists and then merging those two lists together.Merge sort guaranties O(nlog(n)) |
answer: Mergesort works, but you don’t need to use it in this case.Since the two lists are already sorted, just iterate through them both at the same time, appending the next-highest element from the two lists into a new list. O(n+m) time. |
answer: Merge procedure from Mergesort. explanation in cormen |
question :
Cure world hunger. |
answer: Assuming I am the United States Federal Government, I would eliminate all farm subsidies to US farmers. I would re-appropriate that same money (some $6+ billion ) and buy food from local farmers in countries where people are hungry. Currently, farm subsidies encourage US farmers to dump US grown products in hungry countries. This new strategy would not only feed people, but also help grow local economies, helping alleviate the structural causes of hunger and poverty. |
answer: knowledge n money cn buy 2 anything u want….i wud’ve created jobs that could meet the needs of every section of the society….n wud’ve set up free schools for all underprivileged children as well as adults… |
answer: condoms |
answer: "knowledge n money cn buy 2 anything u want….i wud’ve created jobs that could meet the needs of every section of the society….n wud’ve set up free schools for all underprivileged children as well as adults…"Fascinating. Personally, I’d try and find a way to trim the population down to about 2b. |
answer: Recruit the Michael Moores, Roseann Barrs, Alec Baldwins and others (who talk the talk and not much else) of the world to develop means of investing in micro-entrepreneurial spirits (like those who founded Google, Facebook, Glassdoor, etc) and provide them with seed money so they can start local businesses needed by and ultimately supported by locals.The investors win, the business start up wins, the local win and not a penny of government (read "tax payer") money. Geez, how capitalistic. how simple how obvious! |
answer: @ RS. sounds like you’ve been reading Odum’s "A Prosperous Way Down", haven’t you? |
answer: Two methods: one, increase food production so there is enough food to go around; two, reduce the number of people who consume food so there is enough food to go around. |
answer: teach everyone to fish |
answer: Eat mor chickin, as the ad says!!!!! |
answer: How could you cure world hunger? Easy. Destroy the world. If everyone is dead, the problem is cured.Realistically though, as long as there is scarcity in the world, there will always be hunger. If you were to divert enough resources and manpower to feeding every last person, you could theoretically solve the problem. However, such an imbalanced allocation of resources would end up causing huge problems for the world’s economy and leave us all much worse off than we were before. |
answer: Stop trying to beat Nature. We are only delaying the inevitable of when overpopulation consumes all the the resources and commodities (like water) no longer exists for food production. |
answer: That question is so inappropriate I don’t know where to start. I might actually walk out on that one. |
answer: Birth control plain and simple. Control birth rates by people using preventative measures and you reduce birth rates. Providing more food does not solve the problem because they just keep multiplying over and over. Thats why birth control is the only real solution. |
answer: I agree with NR and Mr Guy. |
answer: If someone in an interview looked me in the eye and said, "Cure world hunger," I’d say, "Great. I’d be happy to! Let me know what I have to work with, how large the team is and, by the way, what’s the salary for this? I’m ready." |
answer: ME: I’m glad we’re on the same page. |
answer: How you answer this is telling. If you give up and say it’s not solvable, you’re probably right but toast. I think a good answer says something about addressing global export policy, leveraging first world technology while maintaining ecological integrity, and always keeping local people and resources. |
answer: If I could answer that, would I be applying for this job? |
answer: Sorry to all who say "Grow more", based on my limited knowledge, there is already enough food produced on earth than 8+ billion people can consume it. Infact we are wasting just too much good because of surplus. Story might be different for individual countries though.So we do not need to grow more, nor money is the answer. I think spreading Awareness is the right way to go about it. |
answer: Practice and preach to consume for one’s necessities |
answer: practically you cann’t cure hunger of everyone. Because we infact don’t know what’s a hunger meant for someone? We can suggest the best ways to fulfill it but cann’t feed them with it. So, for example if in case of knowledge, i bet you might not have solid cure. |
answer: replace h with b and n with r…..) |
answer: "hunger" is the effect of a bigger cause, the rich obese people on this earth. Cuttle the food supply to the "Cause" and you would not only end up curing "Hunger" but curing lot of lifestyle illness.1. Ration all food supply.2. Remove the middlemen between the farmers and the consumers. They are eating the profit which in turn increasing the price.3. Encourage people to grow vegetables in their open barren space.4. Reduce corruption and punish people who try to game the process. |
answer: I liked Janet’s answer. I think I would just say I had not realised it was one of the responsibilities of the post I was applying for. |
answer: let me fast for 3 days continuously and get back to you. |
answer: @Abhijit, I don’t think communist-leaning rationing is what Amazon wants to hear. It’s an open-minded and liberal but capital-driven company that believes in competition.In fact they’d respond better to the opening of markets – and moreover information sharing that allows resources to be diverted to where they’re needed. For example, cell phones have been used by fishermen in rural India to identify which markets are paying what prices, allowing them to bring their goods to the markets with higher demand, and allowing less fish to go to waste. |
answer: 1. Become president2. Cut 75% of Federal programs and about 20% of taxes. (studies have shown that cutting the taxes will actually somewhat increase revenue by increasing incentives for entrepreneurs)3. Use tax revenue to increase nuclear storehouses and temporarily employ medical professionals and sufficiently trained medical students to begin an international project.4. Train medical personnel to diagnose malnourishment and to teach others to do the same.5. Begin in the US by training and enlisting volunteers to A. find the malnourished in the country, and/or doing the same abroad and B. commit to helping to feed the malnourished once found6. Repeat process for every allied country, sending medical personnel to diagnose and train volunteers to assist in finding malnourished and treating/feeding them. Leave staff on call in each country to follow up later.7. Once all of the accomodating countries have been reached, use the renewed support of our friendly nations and our strong nuclear threat to subdue, or depose if necessary, the dictators that tend to intercept funds meant to reduce hunger.8. Repeat disbursement of medical staff into the final countries.9. Begin process of selling nuclear weapons to the levels before project.10. Use revenue to feed and treat the many malnourished we would find in the last countries. Any revenue left over goes to any additional malnourished we didn’t get to in the previous countries.11. Ta-da! |
answer: with food, of course. |
answer: Did you really just suggest ‘selling’ nukes? That might cure hunger by triggering a nuclear holocaust… |
answer: Insects – they have the highest calorie to body mass ratio of any food. |
answer: This is a logistics question for Amazon.First consider the questioner – they changed an industry from a brick and morter, consumer comes to us model to an online purchase, we get it to the consumer model through superior warehousing/distribution supply chain.Second, consider the facts in the situation: Yes, we are capable of producing enough food to sustain the world’s population. The countries and regions facing hunger issues (basic supply and demand problem) are generally lacking in proper climate conditions, infrastructure, skilled labor, and/or technology to sustain food supplies to their people. Add to that government instability and poor economic conditions which create more barriers as well as food product expirations and spoilage.The problem is now framed in an Amazon relevant context: How do you amass, store, ship and distribute given the barriers and inherent issues of product shelf life? |
answer: This is a ridiculous question. Obviously, if we were in a perfect world where plants didn’t die and gasoline for transporting it didn’t cost you an arm and a leg and if everyone would be willing to work, there would be no world hunger. But to make it go away you would have to make the world perfect, which is impossible. First, you would have to make plants immortal. Already impossible. Second, gas prices would need to be brought down, which seems impossible to us today. Third, you would have to make it so that everyone had to work. This is impossible because some people can’t work and some people are too lazy to work (although they have no problem making tax payers work for them while they have kids and buy useless junk). Bottom line, even if you could get food to all people, some people wouldn’t choose to take it for one reason or another. |
answer: World hunger cannot be cured, the population keeps rising not the food production. Even if the production is raised, it will not meet the demand of 7 billion people. |
answer: Hunger is not a disease to be cured..The issue is to provide food to those who are alive..I would ask those having plenty to start eating less to save them from being obese and provide them to those who had less. |
answer: Have no serious solution I admit but to be serious I believe communism (ok it failed) was closest in history to having solved hunger on a national scale – there are a lot of Chinese and Russians in the world. It must be admitted then that key ideas to a solution are mass labour, mass sharing, and maybe the totalitarianism that ensures it! So its not a perfect world Im envisioning here but a solution to the poser above. Communism is not the end of your life but war plague natural disaster and the resultant hunger could be. |
answer: Here’s an infalliable two-pronged approach:1. End animal agriculture. Over 80% of the grain and soy produced in this country is wasted on livestock to produce a highly inefficient food product that we don’t even need. With the food resources we throw away on livestock alone, we could easily feed 9 billion people.2. Universal access to family planning. All the food in the world is useless without contraception, because the population will simply increase to exceed the carrying capacity once again. As they say, when you feed hungry people, all that happens is they just make more hungry people. So birth control is a must. |
answer: I would devide that answer into two parts:1. If thinking in terms of short-term goals OR2. If thinking in terms of long-term goalsFor 1. I would say the answer be provide or distribute food from developed countries to under- developed or developing countries soo food is evenly distributed and reached to all and secondly develop jobs for every level of societyFor 2. I would say try to decrease or control population, so increase berth control awareness and secondly open free schools to increase literacy rate soo that everyone can work and earn for his/her family… |
answer: Curing world hunger is impossible. If you give a part of Africa, the machines, the seeds, the tools, and the water source, it seems like a great idea. But, what can go wrong?The fields get plowed, the seeds get planted, the water feeds the soil, and the plants grow to maturity. The problem is that many of those from the outlying areas will come in and steal the crops, trample the plants, and contaminate the water supply.Planned development of a guarded farming tract, will help those of that community. As the gardened tracts expand, so does the community. Protection of the crops, as well as the community, will create paying jobs and responsibility within the community. |
question :
Given an array having integers with just one integer repeated thrice, how will you find out which integer is that? |
answer: 1) You can sort it (O(n*log(n))) and find first repeating number (O(n)). But this is too obvious of a solution.2) You can use a hash table of size O(n) to store number of occurrences. This is O(n) solution, but requires additional O(n) memory.3) There must be a trick here, but I can’t seem to find it. XOR is useless, and everything else is slower than or equal to O(n*log(n)). |
answer: @InterviewCandidate: are you sure the other elements aren’t repeated twice and only one element isn’t repeated thrice? Amazon likes asking a question of this form:""Assume you have an array of numbers where each number is repeated an even number of times and only one is repeated an odd number of times. How would you find that number?""This is a clear cut case of XOR and by the looks of the question, I think that’s what the interviewers were going for. |
question :
Find intersection of two unsorted arrays? |
answer: Two ways.Sort both arrays. Use pointers to traverse both the arrays from start and print any matching elements.OrUse Hashmap storing the array element and its count value from first array. |
answer: Since Amazon is particularly fond of hash tables, I’d prefer to use it in the solution. Plus it’s slightly faster than sorting both arrays. public static int[] ArrayIntersection(int[] arr1, int[] arr2) { Dictionary<int, bool> hashTable = new Dictionary<int, bool>(); for (int i = 0; i < arr1.Length; i++) { if (!hashTable.ContainsKey(arr1[i])) { hashTable.Add(arr1[i], true); } } List<int> list = new List<int>(); for (int i = 0; i < arr2.Length; i++) { if (hashTable.ContainsKey(arr2[i])) { list.Add(arr2[i]); } } return list.ToArray(); } |
question :
Q) How would you all values from the nodes of a given binary tree into a string and then deserialize the string and put it back in the binary tree? |
answer:
This post has been removed. Please see our |
answer: Read the btree in pre order and and put it in to the string, so that you can deserialize the string to construct the btree as before. |
answer: This is ridiculously hard question for a SDET Intern position. Yeah, you can do the psuedo code thing with preorder traversal, no biggy, but my understanding is that they actually ask for a real code on the white board. Good luck writing it if you’re not a seasoned developer. |
question :
Given a target point and a stream of points to be read from a buffer; calculate the distance from each point to the target point. Maintain a list of size N, which contains the N smallest distance values. Assume the stream of points is high volume, i.e. one million per second. |
answer: a list of size N is an indication that the data type should be an array.First step:Compare the target with the item/cordinate in the buffer. This depends on the type of data that is coming in. If it is a coordinate use distance formula.If you compare with every element that comes in, some maybe bigger, some maybe smaller. so the only way is to take a 100 points that come in and get the smallest among them. this can be done by storing the first few values into a variable. then maybe take the average.may be you can do this several times and take the smallest average number. after that what ever comes in, if smaller than the average, store it., then compare with the next. If the new element is smaller, discard x and store the new x. |
answer: a list of size N is an indication that the data type should be an array.First step:Compare the target with the item/cordinate in the buffer. This depends on the type of data that is coming in. If it is a coordinate use distance formula.take a few points and find the distance between the two. may be you can do this several times and take the average number. after that what ever comes in, if smaller than the average, store it. |
answer: The problem I got stuck on is: when you calculate a distance value, how do you know if it’s smaller than the largest distance value in the set of N smallest values.You can’t just compare to the last computed value, you have to compare with the largest distance value in the set of N smallest values.One way it to search the N values every time a new point is processed, but this is not a good solution because it will be too slow when processing a million points per second. |
answer: The answer is Min Heap. |
answer: @rohit and how are you going to maintain a list. if its a min heap tree wouldnt you have to transfer it all into a list which consumes resources?i think the problem is its slow if you are comparing to every element, just do that a few times, until you have an estimate of the large number and then everything that comes in is a onetime comparison |
answer: rohit, it has to be maxheap.lets say its not a stream. u insert first n values in the array and maintain heap property. when u consider a point, u calculate the distance and compare it with element at top. it goes into heap only if its less than heap.now consider second constraint.. million points/sec seems ridiculous amt of data to do this process. we have to use reservoir samplin to pick the points to compare with and maintain the heap. (solution will not be absolutely correct solution though). |
answer: Rohit has it right, it is a min heap.@birbal: You can represent a binary tree in an array where the root is stored at 0, and successive children are stored at 2i + 1 and 2i + 2, where i is the current index.Once the min heap is created, the largest n/2 values will all be stored in the leaves. We know that replacing one of the n/2 largest values will be O(logn) time, and we can expect this time. However, if we were to use a max heap, like anony suggested, we would have to reorder the heap millions of times per second, which is more costly than O(logn). Thus, a min heap is ideal. |
answer: An edit to what I just posted above:I messed up my train of thought; since n is fixed, we know that the leaves of the trees will be fixed in n/2 positions in the array. We can check these positions in n/2 time to see if we can just replace one of the values in the larger half, as we expect them to be replaced before any of the others. Worst case scenario is we have to reorder the heap from the root, but as time goes one, and we get millions of positions closer to our target per second, we can amortize with the expected time to replace one of the largest n/2. |
answer: Hi, I have my second round in a few days. Are you done with your interview? How was your experience? Could you please give some idea of how your interview went?Also, in case you’re not yet done with your interview, then good luck! |
answer: it is max heap. Yes, we have to reorder the heap. Even in min heap, we have to order the heap after placing in leave, which will take same time. |
question :
Given a BST and a target value, find the largest value in the tree that is strictly less-than the target value |
answer: I used an in-order traversal of the tree. So the complexity of my solution is O(n).//Return the greatest value in the tree that is strictly less-than the specified value public T GetGreatestValueLessThanData(T data) { Stack<BinaryTreeNode<T>> toVisit = new Stack<BinaryTreeNode<T>>(Count); int result; BinaryTreeNode<T> current = root; T greatestValueLessThanData = default(T); //perform an in-order traversal and search for the data while (current != null || toVisit.Count != 0) { while (current != null) { toVisit.Push(current); current = current.Left; } current = toVisit.Pop(); result = comparer.Compare(current.Value, data); if (result >= 0) { // current.Value = data // current.Value > data break; } else { // current.Value < data // Save this value and continue greatestValueLessThanData = current.Value; } current = current.Right; } return greatestValueLessThanData; } |
answer: I am a little confused, is this not the left node of the given node? Given that it’is a BST. |
answer: Great to see the code, but if we were to just put the summary of algorithm, here it is:(assumption the target-node exists in the tree)- Navigate to the target-node- go to the left child- from this left-child, keep recursively going to the right child until you reach a leaf node- this will be the largest node that is less than the target node |
answer: What if the target value is not in the tree? The algorithm must handle this.What if the target node does not have a left child? |
answer: int Find(const TreeNode<int>* node, int value){ if (node == NULL) { return -1; } const TreeNode<int>* current = node; while(current != NULL) { if (value < current->data) { if (current->left != NULL) { current = current->left; } else { return -1; } } else { if (current->right != NULL) { current = current->right; } else { return current->data; } } } return -1;} |
answer: If the target value is not in the tree, or if the target value is a leaf node, then the previous two solutions won’t work.If the target value is a leaf node and it is the right-child of its parent, then its parent will contain the answer.If the target value is the left most node of a subtree, then the root of the subtree will contain the answer.In those cases, the previous two solutions won’t work. |
answer: Correction on the last post:If the target value is the left most node of a right-subtree, then the parent of the right-subtree will contain the answer. |
answer: Q: What if the target value is the smallest node in the tree? (i.e. left most leaf node)A: Must account for this exception just like the target value not existing in the tree. |
answer: Before you even start coding this mess you must 1st identify ALL exceptions that could arise, which in this case is the following: – target node doesn’t exist – target node is root node and root node is the only node – target node = smallest node in the tree (i.e. target value = 20, and 20 is the smallest number in the tree; therefore – you cannot return largest value < target node)Therefore, all solutions posted above FAIL! |
answer: Hi, I have my second round in a few days. Are you done with your interview? How was your experience? Could you please give some idea of how your interview went?Also, in case you’re not yet done with your interview, then good luck! |
answer: public static int getHighestValue(TreeNode root,int target){ if(root==null) return -1; else if(root.value>=target && root.left!=null && root.left.value!=target) getHighestValue(root.left,target); else if(root.value<target && root.right!=null && root.right.value!=target) getHighestVal(root.right,target); else if(root.value>=target) return -1; // Target <= smallest node. else return root.value;} |
answer: Correction:public static int getHighestValue(TreeNode root,int target){ if(root==null) return -1; else if(root.value>=target && root.left!=null && (root.left.value!=target || root.left.left!=null)) getHighestValue(root.left,target); else if(root.value<target && root.right!=null && (root.right.value!=target || root.right.left!=null) getHighestVal(root.right,target); else if(root.value>=target) return -1; // Target <= smallest node. else return root.value;} |
answer: package Tree;public class FindBiggestLeastNode { public int find(BTN root, int value) { int res = -1; if( root == null) return res; if(root.value < value ){ res = Math.max(find(root.right,value),root.value); }else { res = Math.max(res, find(root.left, value)); } return res; } class BTN { public BTN left; public BTN right; public int value; BTN(BTN l, BTN r, int v) { left = l; right = r; value = v; } }} |
answer: Find predecessor. |
answer: The cleanest solution is the very first one posted here – inorder traversal.Do an inorder traversal of the tree. This takes O(n) time, and spits out a monotonically increasing, sorted list. Then, walk the list from smallest to largest, until you encounter either the number in question, or a number larger than the one in question. Then return the *previously* visited number from the list (if the target number is smaller than any in the tree, there will be no ‘previously’ visited number and you’d return null).This will work for all cases, including:- target number in the tree vs. not- duplicates in the tree (unlikely in a BST)- target number is smaller than any in the tree- target number is the largest- tree has a single node |
answer: Previous_node = 0;void BT_InOrder(pTreeT root?value) { if (NULL != root) { BT_InOrder(root->left); if(root->value < value) Previous_node = root->value Else return Previous_node; BT_InOrder(root->right); } } |
question :
Given a number find it is one less than the power of two. |
answer: The question could have been a little more detailed, most of the guys who took up the test could not understand this immediately. |
answer: Given a number N, XOR it with N+1 = powers of 2 will give all 0s |
answer: @Anonymous. That’s not true. 3 in binary is 11 and 4 is 100, if you XOR 011 and 100 you will get 111, not 000.I think you meant to say that all numbers will be 1s. |
answer: N xor (N+1) = 2*N + 1 |
answer: If the least bit is 1, then it is equal to N less than power of 2if ( n << 7 ) cout << "It is one less than power of 2"For example1 – 0000 00013 – 0000 00115 – 0000 01017- 0000 0111 |
answer: // the power of two is always has the first bit set to1 and rest all would be set to 0. And one less than power of 2 has all the bits set to 1 except the fist bit.for example 16 = 10000 and 15 = 01111Now if you do bit operation & on 16 and 15, you get zero.Hence, below is the code.public boolean oneLessPowTwo(int num){boolean b = false;if(n & n+1 == 0){b = true;}return b;} |
answer: the power of two is always has the first bit set to1 and rest all would be set to 0. And one less than power of 2 has all the bits set to 1 except the fist bit.for example 16 = 10000 and 15 = 01111Now if you do bit operation & on 16 and 15, you get zero.Hence, below is the code.public boolean oneLessPowTwo(int num){boolean b = false;if((num & (num+1)) == 0){b = true;}return b;} |
answer: A one line answer to this question is: -1 + 2 to the power of -2 – language binary string prefix + length of binary string for NIn Python: 2**(len(bin(511))-3)-1Simple one line in any language with a function to convert int to binary string. |
answer: 8 anwer |
question :
Reverse a list in C++ |
answer: traverse the list until you see null, then backtrack(using recursion), print as you back track.void traverse(node okay){if(ok.getNext() != null){ traverse(ok.getNext());}elseprintln(ok.getValue());} |
answer: sorry there is no else on the above answer |
question :
Difference between an array and a linked list |
answer: in an array you have to specify the size before you implement it. in a list you can increment the size as you add new values |
answer: Not really..we can create an array dynamically as well using malloc..I think they were looking more of access times.For example array access is O(1) i.e constant using the index operator while a linked list access is O(n) |
answer: "Not really..we can create an array dynamically as well using malloc.."Eh? Typically, when referring to an array, we assume fixed size. Having a resizable array implies a dynamic array.http://en.wikipedia.org/wiki/Array_data_structure#Array_resizingAs for the question:An array is of a fixed size; to expand or shrink an array, you must allocate a new array of the desired size, and copy the elements from the original array, which takes O(n) time and cannot deallocate the original space until copying is done. Whereas in a linked list, you can just add a node to the list in O(1) time at the head (or O(n) time if inserting to the tail without a tail pointer), and requires only the space allocated for the new node. The linked list is less costly for resizing, in this sense (dynamic arrays, however, are amortized O(1)).Secondly, an array is sequential in memory, whereas a linked list consists of pointers, and can be scattered throughout memory. This makes arrays better for caching and localization.Third, an array is always indexed, which makes retrieval/insertion O(1) time, whereas a linked list is O(n) for retrieval, and O(n) for insertion to the tail (without a tail pointer). |
question :
Explain Depth First Search and Breadth First Search. Write a routine to traverse the nodes of a binary tree using BFS |
answer: use a stack. |
answer: Queue, rather |
question :
Given an array of positive integers, print out all the numbers which are repeated an even number of times ? Can you do this without using additional storage ? |
answer: If you use additional storage such as a hash, you can do this in O(n). if we don’t then worst case would be nlogn as we can sort and then the same number should be adjacent to each other. |
answer: nlogn sort algorithm |
question :
What is factory? |
answer: a factory is an object for creating other objects. It is an abstraction of a constructor, and can be used to implement various allocation schemes. |
answer: "a factory is an object for creating other objects. It is an abstraction of a constructor, and can be used to implement various allocation schemes."This is partially correct. Factories as more efficient at creating objects. Sometimes the objects are pooled and pre-created to be handed off. This helps deal with the initial slowness of creating a fresh object by allocating memory for it.Usually a factory hands off a cleared out Object ready for its properties to be set or used. |
question :
1. In an array provide pairs of numbers that add to a particular value 2. In fibonacci series provide sum of all even numbers |
answer: 1. Do hashing of all the numbers. The in the 2nd pass for every number in the array x find the number k-x if it exists in the table.2. Generate fibonacci series in the usual manner and then put a condition that if the term is even then add it to the sum |
answer: 1. Do hashing of all the numbers. The in the 2nd pass for every number in the array x find the number k-x if it exists in the table.—————————–What if we try to achieve the same thing in one passSay we have an array with [1,7,3,5,2,9,8,6]And we want to find all pairs that add to 10Iterate through the listFor each element n in the list, figure out if there exists a key in the hashMap with value ’10-n’. If no, add ‘n’ as a key with value null. Else add ‘n’ as a value for key 10-n.After scanning the list print out all pairs from the hashMap with no null values.Map will look likeKey Value1 97 35 null2 86 null |
answer: @AnuradhaTrying to achieve he same thing in one pass is more costly, it will run in O(n^2). You would have to check each value against the rest of the values, resulting in n^2 comparisons. If we implement it with a hash table, we run in O(n) comparisons. |
answer: Oops, I think I misread your implementation, Anuradha. Your implementation is an improvement, my bad. |
answer: 2. You can note a few things here. First off, if you enumerate Fibonacci numbers from 1 (meaning a1 = 1, a2 = 1, a3 = 2, a4 = 3, etc) you will notice that only numbers which index is divisible by 3 are even. Then, you note that those numbers are: 2, 8, 34, 144 etc. And even more, 34 = 4*8 + 2, 144 = 34*4 + 8, etc. So all you need to do is find target’s number (its index), divide by 3 and then build up results using the formula I provided before (an = a(n-3)*4 + a(n-6)).I still feel like there is a more generic formula for this one, without step-by-step addition, but TBH this question is not likely to come up again, so I will stop trying |
answer: public static void findPairs(int a[], int n) { Arrays.sort(a); for(int i=0, j = a.length-1; i<j;) { if((a[i]+a[j]) == n) { System.out.println(a[i] + " " + a[j]); i++;j–; } else if((a[i]+a[j]) > n) j–; else i++; } }The complexity is O(nlogn + n) -> nlogn for sorting and n for printing the pairs(actually n/2). |
question :
Q1) Implement hash table |
answer: Basically think and tell data structure you would choose, why and how would u implement the logic of hash table and will your logic/code execute in O(1) time. Justify all decisions you take at each step |
answer:
This post has been removed. Please see our |
question :
Q2) Certain Customers buy kindle on day one and certain customers buy kindle on day two. Design an algorithm(optimum) to find customers who bought on both days. Each customer has a unique ID (Integer). (I forgot to consider case of duplicates,until she reminded), You need to write complete code(NOT just pseudo code within given time and read it out) |
answer: Understand the question(Find Intersection), take right data structure(Arrays/List), see what operation needed to be performed on that data structure and how would you return the result. Consider edge cases. Propose optimal solution |
answer: We need a little more information about the data. Are there two lists of customers (one list with people that bought a kindle on day one, and another that bought a kindle on day two, for example)? Or are we given a list of customers, from which we can determine which days they bought kindles?If we are given two lists of customer IDs, each representing customers that bought kindles on each day, we can put all of the customers in the first list into a hashtable using the customer ID as a key and setting the value to null, and then iterate through the second list, and check if the customer ID already exists in the hash table. If it does, then we can update the value of the respective key in the hash table to a non-null value, and return the list of those keys. This is O(n) time. |
answer:
This post has been removed. Please see our |
question :
Q3) Few questions on design patterns(Interpreter/ Observer/State) etc. |
answer: general questions on design patterns to know if u know it and your understanding |
answer: Did they go into specifics? There are many design patterns, and I don’t think think they would expect you to know how to code every single one, just the main ones like Factory, Singleton, Strategy, Observer, Decorator, Template, etc |
answer: Nope, just probed a little to know what particular thing means, why would you even consider implementing such a pattern, an example scenario where you would need ,let’s say decorator for example. Also they don’t expect you to code every single one you can very frankly tell i’ve had no experience working with "asked" pattern, and ask courteously – can you tell me what this pattern does(shows your curiosity in subject). I wasn’t asked to code any design pattern, i would have if it was any one of the one i already implemented, but i guess they wont ask you to code what you know, focus is basically on fundamentals with data structures and algorithms. Oh they do ask design a system in which they’ll automatically see ur OOP & OOD skills. I’ll post more, if i make it through to next round. *touchwood* |
answer: Hi, I have my second round in a few days. Are you done with your interview? How was your experience? Could you please give some idea of how your interview went?Also, in case you’re not yet done with your interview, then good luck! |
question :
1) Write a prime number service in language of your choice. how you scale it. 2) design an airline company in object-oriented way. |
answer: public static boolean isPrime ( int number ){ if ( number < 0 ){ return false; } if ( number <= 2 ){ return true; } if ( number % 2 == 0) { return false; } for ( int i = 3; i < Math.sqrt( number ); i = i+2){ if ( number % i == 0){ return false; } } return true; }Simply call this for all odd numbers. And print each one when true. |
answer:
This post has been removed. Please see our |
question :
How would you implement a binary search algorithm for a tree-type data structure? |
answer: convert the tree into a binary search tree. you will not have memory loss, if for every node you create, you delete one from the tree. |
answer: i wish they ask these kind of questions when i interview with them next week |
question :
Given two linked lists, find out IF they intersect. |
answer: Traverse both the linked lists and check if their last elements are the same (address of the elements). |
answer: Solution 1: Traverse the first linked list and mark visited nodes. Traverse 2nd linked list of, the moment we obtain a visited node that’s the intersection point.solution2: If size of 2 linked list are different then traverse the bigger linked list to that extent where the remaining length would be same as the smaller one. Then start traversing both the list together. The moment comment address location obtained, that intersection point. |
answer: HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Integer i : list1) map.put(i, i); for (Integer j : list2) { if (map.containsKey(j)) return true } return false; |
question :
Consider a simple array. What is the time complexity to insert, search, delete an element? |
answer: Constant |
answer: Its O(n).. not constant! |
answer: You’re both wrong it’s constant time to look up an element at an index. Insert and delete are dependent on implementation, most languages require you to re-size or make a new array, so it’s n/a for the most part. And search (if you mean find an element with value x) is O(n) (at worst). |
question :
In linux, a folder consists of 10000 files and some files contain US phone numbers. What would you do to display the names of files containing US phone numbers? |
answer: Use the grep command with some regular expression for the phone numbers. (What I missed in the answer was USE THE "ls" command along with the above answer) |
answer: find someFolder/ -type f -print0 | xargs -o grep "[[:digit:]]\{3\}[ -]\?[[:digit:]]\{4\}" |
answer: jz has it. Maybe throw in another :digit: for area code. |
answer: To build on jz’s answer:find . -type f -print | xargs grep -l "[0-9]\{3\}-[0-9]\{3\}-[0-9]\{4\}" |
question :
The client has complained about your website that it runs very slowly. How would you increase the speed of the website? |
answer: Use less images and more css. Move possible code to client side. Remove unnecessary postbacks.(He asked me if I knew about some tool to do this automatically. I didn’t know that apart from some firefox plugin) |
answer: Cache |
answer: run a free tool (such as YSlow) to see any suggestions. Replace Image stylings with CSS (such as rounded borders with border-radius rather than images). Move CSS to beginning of page, put as much of your scripts into one file as you can (less objects to fetch), compress your javascript and css with a tool (such as yui-compressor)You could also use a CDN such as Google’s Page Speed Service or (maybe what interviewer was hinting at) Amazon’s Cloudfront |
question :
2 stacks are given, one is full of numbers and other in empty, one integer variable is given, fill the 2nd stack with numbers in ascending order with space and time constraints. |
answer: O(n^2)Stack *st1 = new Stack(n);Stack *st2 = new Stack(n);Stack * st;int temp;while(st2->top() != n){ temp = st1->pop();while(!st1->empty()){ if(temp > st1->peek()) { st2->push(temp); temp = st1->pop(); }else st2->push(st1->pop());}st = st1; st1= st2; st2=st1;st2->push(temp);} |
answer: The above won’t work with out little modification. But u can still do that O(n^2) time |
answer: Assuming Stack class throws when you try to Pop an empty stack:Main(string[] args){ try { while (true) { int var = st.PopValue(); emptySt.Push(new Node(var)); emptySt.BubbleUp(); } } catch { }} public void BubbleUp() { Node curr = this.head; if (curr == null) { return; } while (curr.Next != null) { if (curr.Value > curr.Next.Value) { curr.Value ^= curr.Next.Value; curr.Next.Value ^= curr.Value; curr.Value ^= curr.Next.Value; curr = curr.Next; } else { break; } } } } |
question :
Having an infinite supply of water and two containers, one for 3 liters and one for 5 liters, how would you measure 4 liters? |
answer: 1. Fill and pour 3 liters into the 5 liter container2. Refill 3 liter container, transfer as much as possible to the 5 liter container3. Retain the one liter left in the 3 liter container, empty the 5 liter container4. Transfer the one liter from the 3 liter to the 5 liter container5. Refill the 3 liter and transfer it to the one liter in the 5 liter container…5. Fill |
answer: That was the exact algorithm I came up with after some 2-3 minutes of thinking (I don’t know whether that was rated a good or bad time, but it’s interesting to know I’m not the only one who devised it).My wife, though, took 45 seconds to answer with something I didn’t thought in: "have both containers half full". I find it interesting since I NEVER thought of such a simple solution (though more constrained: it relies on the container being somehow regular shaped). |
answer: Fill 5 and Pour into 3Empty 3 container and fill left 2ltrs from 5 to 3Fill 5 and pour into 3 (now u left with 4 ltrs in 5ltr container) |
answer: This is from the movie Die Hard: With a Vengeance. I’m surprised that anyone would use THIS as a question! All it shows is that you watched the movie! |
answer: This reminds me an another question:You’ve 5ltr & 7ltr container. You’ve to get 6ltr out of it. |
answer: You fill both to the brim and empty half of each. This applies to the 5ltr/7ltr question as well. |
question :
Write a function to search for a string within another string. Analyze it’s complexity, and propose optimizations. |
answer: Represent the string in Suffix Tree and u can find the pattern in O(m) time. |
answer: Use Boyer-moore algorithm. |
answer: @jimmy thankshttp://www.movsd.com/bm.htm |
answer: I wonder if you had to code BM algorithm during the interview. That would be… hard… |
answer: Use Robin-karp or KMP algorithm |
question :
Write a function to obtain a string with the binary representation of an integer |
answer: // it’s caller’s responsibility to delete the memorychar * conv_int_to_binary(int data){ int size = sizeof(data)*8; char *binString = new char(size); for ( int i = 0; i < size; i++) { binString[i] = (data >> i)&1; } return binString;} |
answer: void bin_string(int data){ char binString[10]; int i=0; while(data!=0) { binString[i++]=((data>>1)&1)+48; data=data>>1; } binString[i]=’\0′; cout<<binString<<endl;} |
answer: static void bin_string(int n) { String bin = ""; int i = 0; do { bin += (char)(((n) & 1) + 48); n = n >> 1; } while (n != 0); } |
answer: You need to do a reverse string at the end |
answer: length = (int) (log (num) +1) ; // log to base 2while ( (num/2) > 0)){ rem=num%2; binary[length-i-1] = rem; num=num/2 ; i–;} |
answer: No one has handled the case for negative numbers.We need to represent negative numbers in either 1s or 2s compliment |
question :
write a function to print the frequency of characters eg. Input : aabbbc Output: a2b3c1 |
answer: Complexity is O(n)class CharsFrequency { public static Hashtable CharacterFrequency(string strInput) { Hashtable ht = new Hashtable(); foreach (char item in strInput) { if (ht.ContainsKey(item)) { ht[item] = Int32.Parse(ht[item].ToString()) + 1; } else { ht[item] = 1; } } return ht; } } |
answer: Easier method without hashtable int count = 0; for (int i = 0; i < string.length();i ++) { count++; if (i < string.length()-1) { if (simple.charAt(i) != string.charAt(i+1)) { System.out.print(string.charAt(i) + "" + count); count = 0; } } else if (i==string.length()-1) { //last character System.out.print(string.charAt(i) + "" + count); } } |
question :
you have array with n elements. How would you do circular shift of k positions? Time and space complexity? |
answer: Make a circular linklist, and move headpointer K position to do K shifts. It’s O(n) time complexity. Space is contant. (circular link list). |
answer: Well, space isn’t constant because you took an array and then copied it somehow to a linked list. Remember, you were given an array?If I understand the question correctly, they’re asking to do a circular shift of some range of values, like the first k values in an array of length n? So if you wanted to shift right,temp = array[k]from index=k to 1 array[index] = array[index-1]array[0] = tempthis would be O(k)? I mean, it would take k steps, but maybe it’s somehow still O(n) |
answer: oh, sorry, I misunderstood. Not k values, move everything k positions. Praveen Chettypally’s answer works but the space complexity would be O(n) since there is a fully copy of the list?The simplest would probably be to make another array and copy in, starting at the (n-k)th element, going to the end, then starting at the beginning. A second array would probably be a better option than a completely different data structure.What if it has to be done in place? is there an O(n) solution? |
answer: alright -http://stackoverflow.com/questions/876293/fastest-algorithm-for-circle-shift-n-sized-array-for-m-positionshiftArray( theArray, M ): size = len( theArray ) assert( size > M ) reverseArray( theArray, 0, size – 1 ) reverseArray( theArray, 0, M – 1 ) reverseArray( theArray, M, size – 1 )O(n) with no extra storage. Wish I could have thought of that one myself… |
answer: I beieve this does the trick too: public static String shiftArray(char[] inputArray, int shiftLen) { assert(inputArray != null); int length = inputArray.length; assert(length > shiftLen); int moves = 0, from= 0, to = 0; char next, last; to = (from + shiftLen) % length; next = inputArray[from]; while(moves < inputArray.length) { last = inputArray[to]; inputArray[to] = next; next = last; from = to; to = (from + shiftLen) % length; moves++; } return String.valueOf(inputArray); } |
answer: I tried the above function – shiftArray and the looks is not working:shiftItemsFromList class:class shiftItemsFromList{ public static String shiftArray(char[] inputArray, int shiftLen) { assert(inputArray != null); int length = inputArray.length; assert(length > shiftLen); int moves = 0, from= 0, to = 0; char next, last; to = (from + shiftLen) % length; next = inputArray[from]; while(moves < inputArray.length) { last = inputArray[to]; inputArray[to] = next; next = last; from = to; to = (from + shiftLen) % length; moves++; } return String.valueOf(inputArray); }}Part of the main function: System.out.println("Circle Shift N size array for M possitions:"); char [] array = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’}; shiftItemsFromList sh = new shiftItemsFromList(); String s = sh.shiftArray(array, 2); System.out.println("Print the Circle Shift N size array: " + s); System.out.println("DONE");OUTPUT:Circle Shift N size array for M possitions:Print the Circle Shift N size array: cbadafDONE |
question :
You have dictionary. How would you design function/system that should return true/false for check if a word is in a database? How would you scale your solution if word db does not fit in memory/disk? How would you scale it to really big db of words that should be located on n computers? |
answer: You’d enter the words into a binary search tree, which should be able to search down to a word in log(n) time, with n being the total number of words. If your db doesn’t fit on one PC, then you’d place subtrees on different machines and have a master index, indicating which machine had which letter or prefix. For example, if you had 26 machines available, you could put a piece of the tree that corresponds to a letter on each machine. You’d structure the tree so the top node was as close to the middle of the set of possible values on each machine. While this would take some preparation, you’d get fast searches and relatively easy insertions of new nodes. |
answer: For dictionaries that fit in memory, a hash table will suffice. For larger dictionaries, you can use a bloom filter backed by an on-disk b-tree. To scale to multiple computers, you can hash the search word and use a token ring to consistently determine which node that word would exist on, then on each individual node use the bloom filter and b-tree. |
question :
Suppose you have an array of positive and negative integers. Given X as input, find two numbers that add up to X. |
answer: public void findNumbers(int[] arr, int x) { int sum; int y = 0; int z = 0; boolean found = false; int len = arr.length; for (int i=0; i<len-1; i++) { for (int j=i+1; j<len; j++) { sum = arr[i] + arr[j]; if (sum == x) { y=i; z=j; found = true; break; } } if (found) break; } if (found) { System.out.println("The values are : " + arr[y]); System.out.println("The values are : " + arr[z]); } else { System.out.println("The values are NOT found"); } } |
answer: If the input is X. and the values we are looking for are v1 and v2.We create a hash table.We iterate over the array items (V).We lookup the hash table for the value of (X- V).If found, then we have found v1 and v2.else hash the item (V) and get the next item from the array.This should take about O(n) |
answer: class FindTwoNumbersAddingToXInput { public const int size = 10; public const int outSize = 2; public int[] Ints = new int[size]; public int[] output = new int[outSize]; public FindTwoNumbersAddingToXInput() { Random rnd = new Random(); for(int index = 0; index < 10; index++) { Ints[index] = (int)(Math.Floor(rnd.NextDouble() * 10)); } } public int[] FindTwoIntsAddingToXInput(int X) { Hashtable ht = new Hashtable(); for(int i = 0; i < Ints.Length; i++) { if(!ht.ContainsKey(Ints[i])) ht.Add(Ints[i],1); } for (int i = 0; i < Ints.Length; i++) { int diff = -1; if (X > Ints[i]) { diff = X – Ints[i]; } else { continue; } if(ht.ContainsKey(diff)) { output[0] = Ints[i]; output[1] = diff; break; } } return output; } } |
answer: Intent is if you can even design (flowchart too i hope ??) how to approach this prob that consumes least space and time. Its more like puzzle solving. I don’t claim myself to be best but I do believe amazon is not looking for people who know how to use collection frameworks. Here is my humble solution.Give list A and input X. Say list is like {-4, -3, -2, -1, 0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} and input = 101. Create list B, C.2. Choose half of input so here pivot = 10/2+1= 6 (5 is not present so won’t repeat)3. Iterate thru list A and populate list B such that4. B: Sorted list of nos. <6 C: reverse sorted with nos.>=6B: -4, -3, -2, -1, 0, 1, 2, 3, 4, 5C: 15, 14, 13, 12, 11, 10, 9, 8, 7, 6.5. Iterate thru the list B and internally iterate thru list C.6. I think using this method one won’t have to iterate till the end. If you pick -4 then 14 is right there as second element. Will reach worst case for 4 where you will iterate C till the end.It will still be O(n square) but better than iterating thruout.I am myself sure this is not the best soln so pls don’t bombard me. |
question :
Test if a Binary tree is BST or not |
answer: –> Perform an inorder travesal on the BT and save the values in an array.–> Check if the array is sorted, if sorted then the binary tree is a BST. |
answer: struct Node{ Node *left; Node *right; int item;}void InorderTraversal(Node n, int arr[]){ if(n!=NULL) { InorderTraversal(n.left); arr = n.item; arr++; InorderTraversal(n.right); }}bool isOrdered(int arr[]){ for(int i = 1; i<(sizeof(a)/sizeof(int)); i++) if(a[i-1]>a[i]) return false; return true;}int main(){ BT tree; int* arr = new int[tree.count]; InorderTraversal(tree.node, arr); bool ordered = isOrdered(arr); if(ordered) cout<<"Tree being is ordered"; else cout<<"Tree being is not ordered"; delete[] arr; return 0;} |
answer: struct Node{ Node *left; Node *right; int item;}void InorderTraversal(Node n, int arr[]){ if(n!=NULL) { InorderTraversal(n.left); arr = n.item; arr++; InorderTraversal(n.right); }}bool isOrdered(int arr[]){ for(int i = 1; i<(sizeof(a)/sizeof(int)); i++) if(a[i-1]>a[i]) return false; return true;}int main(){ BT tree; int* arr = new int[tree.count]; InorderTraversal(tree.node, arr); bool ordered = isOrdered(arr); if(ordered) cout<<"Tree being is ordered"; else cout<<"Tree being is not ordered"; delete[] arr; return 0;} |
answer: You don’t need to store anything in an array. Just keep track if each next node is greater than the last while you traverse. |
question :
Write a function that takes an integer and prints out the digits separated by commas. Example, pass in 345 print out 3,4,5 |
answer: Void parseDigits(int Number){string format = ""';while(num > 0){quotient = num%10;if(num > 9)format = format + quotient.ToString() + ",";elseformat = format + quotient.ToString();num = num/10;}Format.Reverse(); //should give desired number with digits seperated with comma;} |
answer: without reverse:firstdig = num/100 ;integer division will give you first digitprint firstdigprint ","num -= firstdig * 100seconddig = num/10print seconddigprint ","print numnum -= seconddig *10 |
answer: slightly lazier version: public static void printIntStringMath(int theInt) { StringBuffer result = new StringBuffer(); while(theInt > 0) { result.append("," + theInt % 10); theInt = theInt / 10; } result.deleteCharAt(0); System.out.println(result.reverse()); } |
answer: public static void main(String [] args){ int j = 345890; String line = j+""; int len = line.length(); int i = 0; while(i<len){ System.out.print(line.charAt(i)); if(i !=len-1) System.out.print(","); i++; } |
question :
Write out merge sort and apply it to two arrays of integers. |
answer: in Java:static void sort(int[] arr, int low, int high) { int middle = (low + high) >> 1; if (low < high) { sort(arr, low, middle); sort(arr, middle+1, high); merge(arr, low, middle, high); } } static void merge(int[] arr, int low, int middle, int high) { int[] temp = new int[high+1]; int saveLow = low; int saveHigh = high; int startHigh = middle+1; int ctr = 0; //merge them together while(low <= middle && startHigh <= high) { if (arr[low] < arr[startHigh]) { temp[ctr] = arr[low]; low++; } else { temp[ctr] = arr[startHigh]; startHigh++; } ctr++; } //if high part ended first, finish the low part if (low <= middle) { while (low <= middle && ctr <= temp.length) { temp[ctr] = arr[low]; ctr++; low++; } } //if low part ended first, finish the high part if (startHigh <= high) { while(startHigh <= high && ctr <= temp.length) { temp[ctr] = arr[startHigh]; ctr++; startHigh++; } } //copy temp value into real array ctr = 0; while (saveLow <= saveHigh && ctr <= temp.length) { arr[saveLow] = temp[ctr]; saveLow++; ctr++; } } |
answer: Good answer, now read this to the interviewer over the phone. |
answer: @rich – they usually have you type it out in shared text editors like google docs or collabedit.. every keystroke will be watched AND questioned |
answer: This looks incorrect as the (low+high) at the top you need to be positions of the low and high not the values. Here you use them as positions, then later on you use them as values. |
answer: " if (low < high) {"Should be a comparison of the values in arr so it should be"if (arr[low] < arr[high])" |
question :
Design a parking lot kiosk. |
answer: Here is what is on my minde.Design: Check-in and Check-Out, Payment module.Check-in and Check-out is used to get check-in time, check-out is used to validate the payment.Payment Module – will contain, verifying the ticket, calculating stay time, validating the credit card / accepting cash, rendering change etc, and charging the amount and giving back the charged ticket successfully.We can define each of the above functionalities into different classes/ methods.If anyone thinks has a better solution please post. |
answer: Software development is about finding the balance between various desired qualities of programs that often come at the expanse of each other. For example, efficiency often comes at the expanse of development time and code complexity. In real world situation, I would begin the design process by thoroughly understanding requirements. I would seek the answers to questions like:-What’s the capacity of the parking lot?-What’s the avg/max/variance of the rate of vehicle input? output?-What’s the tolerance for traffic jam at entrance? exit?-Who are the users? Are they regulars or use the lot only once?-How many entrances? Exits?-What’s the devel time requirmenment?-Is this code a one-off or be reused?Since this is just an interview, I’ll assume that this parking lot has 100 spots, one entrance, which is also the exit and that the input/output rates are low enough that traffic jams are non-issue. When the vehicle enters, the ticket booth issues a time-stamped ticket to the vehicle. When the vehicle leaves, the ticket booth accepts the ticket, notifies the vehicle of the costs and accepts payment. It assumes well behaved drivers that always pay correct amount with exact change.class TicketBooth{public: Ticket onVehicleEnter(); Price onVehicleExit(Ticket); void acceptPayment(Money);} |
question :
Staircase problem: Given a stair of size N and two ways to reach next step, take 1 step at a time or take 2 steps at a time. What is the total possible ways you can reach staircase of particular length? |
answer: Fibonacci series or 2^(n-m)+1 possible ways |
answer: What is n and m in your 2^(n-m)+1 answer? |
answer: @Rich:n = size of stairsm = target length to reach, where if m = 0, m = n.i.e., the top stairs is considered to be the first stair. |
question :
find 2 numbers which summation is a give number |
answer: Simple answer: the Given Number + zero. |
answer: I’m with Wiseguy, I couldn’t think of any other answer, but might get the wrong answer myself if I didn’t hear his obvious answer, because I might think that there’s some off-the-wall that I’m not considering. |
question :
Write a function to display the permutations of a string |
answer: I simply didn’t study this one enough, but it’s another one of the standard terrible questions asked. |
answer: I found this site helpful:http://n1b-algo.blogspot.com/2009/01/string-permutations.htmlHere is my javascript implementation of the case where duplicate characters are allowed, but duplicate permutations are not (using the hash table method described in the blog):function swapElts(arr, x, y) { var temp = arr[x]; arr[x] = arr[y]; arr[y] = temp;}// arr is array of things (characters) to permute// start is an index into arr// res is a list of the resulting permutationsfunction permute(arr, start, res) { if(arr.length == start) res.push(arr.join("")); // save this permutation else { var hashtable = {}; for(var i = start; i < arr.length; i++) { // if element arr[i] is already in hashtable, it is a repeated character, // so do not create permutations of the rest of the arry for it if(hashtable[arr[i]]) continue; swapElts(arr, start, i); permute(arr, start+1, res); swapElts(arr, start, i); hashtable[arr[i]] = 1; // puts element arr[i] into hashtable } } return res;}function permuteString(str) { return permute(str.split(""), 0, []);}permuteString is a wrapper around the recursive permute(). It simply calls permute() passing in the array of characters making up the string, the starting index of 0, and an empty array where results are put. |
question :
Please code up and send me a function that takes two integer arrays and returns their intersection. This answer must take less than n^2 time. |
answer: Use a hash table or tree. |
answer: modify merge sort |
question :
An array consists of elements where each element appears an even number of times. Only 1 element appears odd number of times. Find that number |
answer: One possible solution: (using hash tables)public class ArrayEvenOdd { public static void main(String args[]){ //int[] ele = {‘1′,’2′,’3′,’3′,’2′}; String[] str = {"a","b","c","a","b","c","c","c","c","b"}; Hashtable ht = new Hashtable(); for(int i = 0; i < str.length; i++){ if(!ht.containsKey(str[i])){ ht.put((str[i]), new Integer(1)); } else{ int temp = (Integer)ht.get(str[i]); temp++; //System.out.println(temp); ht.put(str[i], temp); } } Enumeration e = ht.keys(); while(e.hasMoreElements()){ Object o = e.nextElement(); Integer o1 = (Integer)ht.get(o); if(o1%2 == 1){ System.out.println("Element with ODD occurance is " + o); } } }} |
answer: take the element from array one by one and xor it with resultant and asign the value to resultantegint resultant =0;for(int i : arrayOfInt){resultant^=i;}print resultant |
answer: The XOR answer is the best one. The complexity is just O(N). The logic here is that if we XOR the same numbers for even times we will get all 0s. For example:1010 XOR 1010 = 0000Now let’s just assume that we have another number 1101, which will exist odd number of times. (Let;s assume we have only one 1101 for simplicity) . XOR ing 0000 with 1101 will result in 1101. |
question :
Write a code for determining the given integer is palindrome in binaries. |
answer: Reverse the bit of the given integer. Then compare it with the original. |
answer: int palin(int x){ int i, j, flag=0; i=15; j = 17; /* assuming 32 bit integer */ while( x&(1<<i) == x&(1<<j) ){ i–; j++; if(i==-1) {flag=1; break} } if(flag) return 1; else return 0;} |
answer: Add to the candidate.Reverse all the bits by exchanging adjacent bits, adjacent two bits, adjacent four bits, etc…O(log n).. n is the number of bits in the numberThen XOR with original, to see if result is 0, otherwise not palindrome |
answer: import os,sysdef is_palindrome(x): t=x; cnt=0; while t>0: print t t>>=1; cnt+=1; print cnt; for i in range(cnt/2): if ((x & (1 << i)) > 0) != ((x & (1 << (cnt-i-1))) > 0): return False return Trueprint is_palindrome(5) |
question :
i) Given a value v, in a BST find the next value in order. |
answer: I explained the solution, he doesn’t seem to be very satisfied. |
answer: 1. Find the value in by traversing and then when the value is found (in log2(n) traverses atmost),2. Check if rightNode is not null if not then traverse the rightNode->left->left->left… until left !=NULL the last value before null is the next one in orderFor Ex: in wikipedia in the figure, given the value ‘3’ find the next in order.So when we reach 3 we go to right i.e. 6. then traverse left branches only. the last left non-null node is ‘4’. That is the next one in order. |
answer: In case right Node is null, next element = smaller(parentNode, smallest in the right child of parent) |
answer: 3 main conditions:- tree can be null- IN ORDER traversal has finished an V has not been found- do an ‘IN ORDER’ traversal and v is found IF node is a LN ‘leaf’ then parent is the next node in order ELSE IF node is a RN ‘leaf’ then grand parent is the next node in order ELSE IF has right subtree (we should have traversed the left by now) THEN root of that subtree is the next node in order ELSE then again it is parent of the node which is going to be in order (IF parent is NULL then there is no next node in order. ) |
answer: Isn’t it simply finding the in order successor of the given node? |
answer: if it is an BST, how about compare the value?a easy way is to do the inorder traversal , but compare the value with the given value, and whenever it larger than the given value, we have found it.void InorderTraverNextNode(node * root, int givenValue, node * returnNode){ if (root ==NULL) return; InorderTraverNextNode(root->left, givenNode, returnNode ); if (root->value > givenValue) { cout <<"The founded next value is: " + char(root->value) << endl; returnNode = root; return; } InorderTraverNextNode(root->right, givenNode, returnNode );}If this is not BST, I think we can still do this, but simply make a counter, or a flag, but put that flag, such as when found the given key, make the flag = True, and if the flag is true, (when continuing traver…), the next round we’ve already found the results.void InorderTraverNextNode(node * root, int givenValue, bool flag, node * returnNode){ if (root ==NULL) return; InorderTraverNextNode(root->left, givenNode, returnNode ); if (flag ==True) { cout <<"The founded next value is: " + char(root->value) << endl; returnNode = root; return; } if (root->value == givenValue) { flag = True; } InorderTraverNextNode(root->right, givenNode, returnNode );} |
question :
ii) In a file or one million words find a pattern of words. |
answer: Again he was not satisfied with my answer. |
answer: if on unix/linux, grep with regex |
answer: one thing is certain – that we have to go through each and every word – a pattern can be just a substring of a word – this means that we will have to convert that into common patterns say – regex (and the words can be of varying sizes) – do a matching on the regex. hmm…seems a very lousy solution…any other ideas folks? |
answer: http://www.movsd.com/bm.htm |
question :
Write code to find how many 1s are in an integer in its binary form. |
answer: int count =0;while(n !=0){ count+= n&1; n>>1;} |
answer: stackoverflow has the best answerint NumberOfSetBits(int i){ i = i – ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); return ((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;} |
question :
Write code to find the nth fibonacci number. |
answer: You can find the nth fibonacci number in O(log2(n)*log2(n)) computations.Apply recursively ::x(n) = x(n-(k+1))x(k) + x(n-k)x(k+1) where k = pow(2,floor(log2(n)));For example x(12) = x(3)*x(8) + x(4)*x(9)I initially precompute pairs like [x(2),x(3)], [x(4),x(5)], [x(8),x(9)], [x(16),x(17)] and store them in vector. Size of 2 vectors should be floor(log2(n))here’s how the pairs are computed: start of with a=1,b=0iteratively in a loop:x(i*2) = a^2 + b^2x(i*2 + 1) = 2ab – b^2ex: in 5 loops I get x(32) and x(33) i.e. 10 multiplications to compute 33rd and 32nd fibonacci numbers.i=1; x(2) = 1, x(3) = 2i=2; x(4) = 3, x(5) = 5i=3; x(8) = 21, x(9) = 34i=4; x(16) = 987 x(17) = 1597i=5; x(32)= 2178309 x(33) = 3524578I’ve described the algorithm and code on www. optionsbender .com . in the algorithms section |
answer: Recursion is for suckers. int fib(int fibNum) { if(fibNum == 0) { return 0; } else if(fibNum == 1) { return 1; } else { int mMinus2 = 0; int mMinus1 = 1; int mCurrent = 0; for(int i = 2; i <= fibNum; i++) { mCurrent = mMinus1 + mMinus2; mMinus2 = mMinus1; mMinus1 = mCurrent; } return mCurrent; } } |
answer: memoizing would be helpful, else it’ll explode for higher order fibonacci numbers |
question :
Height of a Binary Tree |
answer: Recursive solution |
answer: logn base 2… n is number of elements in the binary tree |
question :
Coding the fibonacci algorithm. |
answer: A fibonacci sequence is a a sequence of numbers in which each number equals the sum of the two preceding numbers. If N is the number then:(0) + (1) + … (N-2) + (N-1)In C, non-recursively, this looks like:int fib(int n){ int first = 0, second = 1; int tmp; while (n–) { tmp = first+second; first = second; second = tmp; } return first;} |
answer: BruteForce is O(n)Can be accelarated by matrix multiplication |
answer: #include<stdio.h>int Fibonacci(int);main(){ int n, i = 0, c; scanf("%d",&n); printf("Fibonacci series\n"); for ( c = 1 ; c <= n ; c++ ) { printf("%d\n", Fibonacci(i)); i++; } return 0;}int Fibonacci(int n){ if ( n == 0 ) return 0; else if ( n == 1 ) return 1; else return ( Fibonacci(n-1) + Fibonacci(n-2) );} |
question :
write a code to print out the fibonacci sequence recursively and iteratively. |
answer: It is pretty straight forward |
answer: //Fibonacci series recursively and iteratively#include <iostream>using namespace std;unsigned long fib2(unsigned int n, unsigned long p0, unsigned long p1){ cout<<p0 + p1<<" " ; return (n == 1 ? p1 : fib2(n – 1, p1, p0 + p1));}int main(){ int n=10; cout << "Fibonacci Series Recursively:: "<<0<<" "<<1<<" "; fib2(n-1, 0, 1); cout<<endl; int p0=0,p1=1; cout << "Fibonacci Series Iteratively:: "<<0<<" "<<1<<" "; for(int i=0;i<n-1;i++){ p1=p1+p0; p0=p1-p0; cout<<p1<<" "; } return 1;} |
answer: this is the simplest question my interview scenarios and find many people fail for it. |
question :
What does <i> and </i>mean? |
answer: Italics / close italics |
answer: <i> I should<i/> I shouldn’t(should I stay or should I go… dada-dada-dada-DA… The Clash!) |
question :
whats the use of virtual destructorr? |
answer: same as any virtual function. the behavior of the destructor can be overridden by inheriting classes. |
answer: The purpose of a virtual dtor is to insure proper destruction in a class hierarchy. Example, class B derives from class A. Pointer of type A pointing to an instance of type B is deleted. Without virtual dtor, only ~A will be executed. With virtual dtor, both ~B and ~A will be executed. |
question :
1=5,2=25,3=125,4=625,5=? |
answer:
This post has been removed. Please see our |
answer:
This post has been removed. Please see our |
answer: 3125.. it is a series with nth term = 5^n |
answer: 5 = 1 based on 1st assumption |
question :
Find nth fibbonacci number in less than 0(n). |
answer: int fib(int n){ int a = 0; int b = 1; for(int i = 0; i < n; i ++){ System.out.println(a); // fib # here a = a + b; b = a – b; }}O(n) complexity. impossible to do it in less then that. |
answer: Of course it is possible. The fibonnacci numbers contain a closed form:F(n) = (1/5^(1/2))*((1+5^(1/2))/2)^nint fib(int n) { return Math.pow((1+Math.sqrt(5))/2,n)/Math.sqrt(5);} |
answer: It is notable that the closed form calculation has complexity O(log n), *if* the Math library’s implementation uses efficient binary exponentiation. If it does not, or for some reason you must implement exponentiation yourself and choose a straightforward iterative multiplication approach, then pow( ) function results in n calculations, or O(n).Also note that, for very small n, the closed form is more expensive than the iterative form. |
question :
Write production quality code to find whether a given binary tree is a BST or not. You can’t make any global variable. |
answer: A BST rooted at node N is defined such that all nodes to the left of N are less or equal to N, and all nodes to the right of N are greater or equal to N. And the left and right subtrees are BST as well.boolean isBST(Node N) { if (N == null) return true; Node L = N.left; Node R = N.right; boolean LV = L != null ? L.value <= N.value : true; boolean RV = R != null ? R.value >= N.value : true; return LV && RV && isBST(N.left) && isBST(N.right);} |
answer: left of N are less or equal to N, and all nodes to the right of N are greater or equal to N – clearly something is wrong here……….it can be either not both (strict inequality for atleast either of the side) |
answer: this blog has a nice O(n) C code..http://justprogrammng.blogspot.com/2012/06/check-if-tree-is-bst-on-code-interview.html |
question :
Find all anagrams in a file. Improve the running time to O(n). |
answer: for each work in the file, sort the letters in the work and add the result into a stack, if there is a collision, the original word is part of set whose words in that set is an anagram. Since adding to a stack only take O(1) and you must visit each word once, the complexity is O(n). |
answer: The way I approach anagrams is that I assign a prime number to each letter and then multiply the letters. In theory, ABC gives you say 3 * 5 * 7 = 105 Any anagram will have letters that when multiplied give you 105.In the solution above, it’s far more than O(n) because of the sort step which depending on how you’re trying to sort could wind up nlogn or n2 or something like that. |
answer: I should note that this is generally good to about 9 characters, at which point overflowing becomes an issue and you’ll probably want to go to some construct such as BigInteger in Java or go with what Anonymous presented. |
answer: @SeanB: Instead of multiplying number just add them. Adding won’t cause a big value for stack overflow or something.(e.g A=1, a=1: b=2, B=2…so on.) Rule of Association in maths. That would do. However even for multiplying or adding we have to split the string which will involve some complexity, therefore that might not make the whole operation o(n). |
answer: @SeanB,thats good idea, adding to that: we can map a prime number for each alphabet. if any string has same multiplied product then both should be anagram.For example:Map the first 26 prime numbers to "abcd….xyz" "1, 3, 5, 7, 9, 11, 13, 17, 19, 23, 25, 29, 31, 37, 41, 43, 47, 49, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97"now consider the anagram: "cinema" and "iceman" the product of the two numbers will be same. Since we use prime numbers, the factors should be same. so its proved that both are anagrams.To check overflow: 97 is for the char "z", and usual word size is 10. So, Math.pow(9, 10) is 73742412689492830000 and which still finite. |
answer: @Jimmy: There is a small flaw in your assumption. Let’s say we take the prime number sequence as 1, 2, 3, 5, 7,,, assigned to A, B, C, D, E etcYour assumption would give out the same answer for "BC" and "D". But these two are two not anagrams. So i guess i better approach would be to multiply the numbers. |
question :
Why do you want to work here? |
answer: If your answer is, "To grow as a professional with professionals" then you’re wrong. |
answer: "To get the employee discount on the amazon products" |
question :
If there are ‘n’ computers connected in a circular node, what is the minimum hop required to reach the diagonally opposite computer, and what is the max possible hops. Use any algorithm to hop through computers. |
answer: Let’s assign node number to the computers from 0 to n-1 . If we calculate the formula there are always 2 paths available between 2 computers. Let’s assure we need to find path between two nodes n1 and n2. Then the length of two would be l1= n2-n1 or l2=n-(n2-n1).So the minimum path would be min(l1,l2) and max would be max(l1,l2). Directions of movement would be chosen accordingly. |
answer: If the l1 and l2 are equal, we can also come to conclusion that two nodes are opposite to each other. |
question :
check whether from the given word a palindrome can be formed or not? |
answer: For making a palindrome, there should be two instances of every unique letter in the word…and optionally, one letter which has only one instance (based on the number of letters in the word).So, check for this condition. |
answer: public static void palindromeFormationStatus(String str) { int [] a = new int[129]; int s = 0; for(int i=0;i<str.length();i++) { a[str.charAt(i)]++; } for(int j=0;j<129;j++) { //System.out.println(str.charAt(j)+"–>"+a[str.charAt(j)]); if(a[j]>0 && a[j]%2!=0) s++; //s = s+ a[str.charAt(j)]; } if(s>1) System.out.println("palindrome cannot be formed"); else System.out.println("palindrome can be formed"); } |
question :
There are ten billion stars in the universe. Figure the nearest thousand stars given a list of X, Y, and Z coordinates. |
answer: Like the other four questions I was pretty sure this was a "see how the kid thinks" question but the interviewer wanted data structures and algorithms described in detail over the telephone including their complexity (big-O notation). I’m sure several readers think this question is easy. I fail to see how this has anything to do with the job description. The other four questions were of a very similar bent and quite disappointing to hear. |
answer: This question is a space partitioning problem. It can be solved using a kDTree.- Find the bounding box of all points – O(n)- Sort the points using the dimension with maximum width – O(nlgn)- Split the points at the mid-point of the chosen dimension – O(1)- Construct a tree by recursively sub-dividing the list [Repeat all the above operations on subdivided list]Once you have the list, you can find the nearest points by searching through the data structure. |
question :
You have 2 employees, Jim, who is new and doesn’t seem to follow the SOP and constantly makes errors and Jane, who is a seasoned veteran, also does not follow the SOP, but rarely makes errors. How would you address with each employee the fact that he/she does not follow the SOP? |
answer: The SOP is the SOP for a reason. Everyone must adhere to it, because it ensures not only accurate work, but also makes it easy for management to identify where a transaction went wrong. If Jane makes a mistake, rare as they may be, it would be nearly impossible to figure out where in the process the error occurred b/c her procedures are her own, not the company’s. |
answer: Jim….The SOP is the SOP for a reason. Everyone must adhere to it, because it ensures not only accurate work, but also makes it easier to identify where something went wrong in the process.Jane…If Jane is a seasoned veteran and is not making mistakes/errors, then there may be something to learn from this…perhaps the procedures are outdated, perhaps there are better ways to achieve to the same result. Would ask that Jane help to lead an effort to document the proper procedure for her area of expertise… obtaining buy in from all the other operators that do her job on the other shifts as well as other stakeholders to the process. This shows Jane that she is valued by her management team as well as will benefit the company with any process procedure improvements. |
answer: this is actually one of the 4 case study scenarios. Do not deviate from what you sent to the recruiter during your live interview |
question :
1) Given an array of numbers where each number has a duplicate except one, write a program to return the lone number. |
answer: Solution 1Use a bit map for all possible numbers.Initialize it with all 0.traverse the array and XOR the corresponding bit for each number.in the final bit map, the bit with 1 corresponds to the lone number. O(n) Solution 2Sort the array, then traverse it. O(n log n), but less memory. |
answer: u can just XOR all the numbers..the result is the lone number |
question :
Questions about the product line of the interviewer, even if that’s not what you’re interviewing for – very difficult to ask a detailed question about something you didn’t expect to be asked about. |
answer: Re: your postAlso no selling in my case. They stress the need for a fit but ultimately(a) they don’t describe themselves as a person(b) some didn’t even say hi(c) overall rude and arrogant impression(c) don’t seem to walk the talk as they focus more on analytics than on people and a customer / service mindsetInterestingly, who in their right minds would want to be a fit for that?(not meant as an insult to the engineers or analysts, of course. Analysis and understanding of the results of course is a major backbone to this company but the customer mindset doesn’t seem to have survived in many respects) |
answer: …no selling of the company during the interview that is. |
question :
How do you implement LRU cache? |
answer: I said a linked list sorted in order of priority along with a hashtable. He wanted the exact details. Kept working them out. |
answer: A cache is basically a map. Put the cache in a stack and you’re done.When a new entry causes stack to overflow, pop the stack and push again. |
question :
4, 7, 15, 29, 59, 117, 235…. whats the next in the series? |
answer: 469n*2 +-1, |
answer: 2*117+235=469 |
question :
What do you think of the offices? |
answer: I admire frugality. |
answer: Tehe, this answer rocks! |
question :
How to find the unique integer in an array, where all the other numbers appear twice. |
answer:
This post has been removed. Please see our |
answer: XOR all the elements into a variable and that variable will have the unique integer. |
answer: XOR will not work … consider that u have array of 4 elements {3,3,3,1}. XORing them all gives u 2 which is incorrect. |
answer: XOR is the right answer because all the other numbers occur only twice. So for {3,3,1} the answer is 1. |
question :
Find the most frequent 3-page sequence in a web log. |
answer: Did you find the answer for this? I am really interested in this answer and would greatly appreciate it if you can provide some pointers. |
answer: MY solution would be to sort the web log by date, and IP. If the user made less than 2-page sequence, then remove that IP.For each 3 possible sequence, add it to a data structure. If the sequence already exists, then increment the count of the sequence. In the end, you can do a search on the data structure to find the 3-page sequence that appeared the most frequent. |
answer: Could you use a hash table where the key is derived from the sequence and the value is the number of times it occurs? |
question :
You have just been given a large program with many different input components. One of the component deliveries was completed with errors and the at group says they cannot fix the problem because they are on to other work. How do you resolve this issue? |
answer: Must do in any case : Communicate – Ensure Management is aware of the failed dependencyPrioritize and Plan: If its critical for your product, propose a plan on what’ll it take to ‘get it done’ |
answer: In this case the deliverr is already made.Create an issuecommuncate to StakeholdersTriage the issue to understant the severity and priority of errorsFor Pri1 Sev1 issue, Trade-off and negotiate to buy back the resources engaged to new project based on the criticality of the current tasks.Manage expectations with customers on when the delivery can be made with the fixes.If nothing works. Apply the roll back plan. |
question :
Given a ring of coins, you want all coins to result in the same orientation (either all having heads, or all having tails). What’s the probability that one of these two scenario’s occurs? |
answer: (1/2)^(n-1) if there are n coins in total |
answer: the possibililty can be either one no doubt about that, it can be head nor tail. it can be a win win situation or loose win situation neither to win loose situation…let say its 10 coins to be toss and you / interviewer go with head and myself / applicant go with tail. if tossed with 5 head and 5 tail thats win win situation and applicant got the job. If 4 head and 6 tail thats loose win situation and the applicant still get the job. And if 6 head and 4 tail thats win loose situation and the interviewer win but for the applicant failed and he did not get the job…then I am / applicant gonna hit the road and look for a new job… |
question :
Write a code to reverse binary bit pattern for an integer without using any string or utility methods? |
answer: hit use bitwise operations like bitwose OR, shift left, and shift right. |
answer: there is rol and ror operations which can be useful to shift places and also the left most digit can move to the end during the operation. |
answer: http://www.intel.com/software/products/documentation/vlin/mergedprojects/analyzer_ec/mergedprojects/reference_olh/mergedProjects/instructions/instruct32_hh/vc270.htmthis might be helpful |
answer:
This post has been removed. Please see our |
answer: unsigned int a=123; // Given numberunsigned int b=0; /// temp variableint i;for(i=0; i<32; i++){ b = b | (a&1); b = b << 1; a = a >> 1;} |
answer: pls ignore my first ans. |
question :
I was asked a puzzle .. You have 12 balls identical in size and appearance but 1 is an odd weight (could be either light or heavy). You have a set of scales (balance) which will give 3 possible readings: Left = Right, Left > Right or Left < Right (ie Left and Right have equal weight, Left is Heavier, or Left is Lighter). You have only 3 chances to weigh the balls in any combination using the scales. Determine which ball is the odd one and if it’s heavier or lighter than the rest. How do you do it? |
answer:
http://www.devenezia.com/misc/12%20Stones.htm |
answer:
Assume the 1 ball to be heavier ( same logic applies for lighter). Divide the 12 balls into 2 groups of 6 each. If the odd-ball is in left then the result is L > R. So now we know the odd ball is in left. Divide the 6 balls into 3 and 3. Assume the odd-ball is in right now. So we get L < R. So we take the right 3 balls. Take 2 balls from them and weigh.Case 1:- L > R, the ball on left is the oddCase 2:- L < R, the ball on right is the oddCase 3:- L = R, the ball which is left over is the odd |
question :
How would you implemented a priority queue that allows one to get minimum and maximum from the same data structure? |
answer: Such a queue is called a double ended priority queue |
answer: www.cise.ufl.edu/~sahni/cop5536/powerpoint/lec10.ppt |
answer: Interesting that a data structure exists for this – I hadn’t heard of that. It does make sense, in that a heap has a lot of "unstructured" space, but I would be hard pressed to derive that in an interview.My initial thought was to simply use a binary tree – min and max can be easily found by strictly moving left and right as far as possible, with log(n) performance. It’s not exactly a priority queue (O(1) < O(log(n))) but it’s pretty close until you get into ridiculous territory (a billion elements requires 30 left/right traversals). |
question :
Find if a linked list has a cycle in it. |
answer: You can define two pointers, slow and fast. Make both of them start from the head. Advance the fast two items at a time and the slow one item at a time. If the link list is acyclic, the fast pointer will reach a NULL. If the link-list is cyclic, you will get to a point where either "fast = slow" or "fast->next = slow". This algorithm is O(n). |
answer: The ISU author’s answer is fantastic. |
question :
Given the function prototype for a function called secondLargest given a pointer to a list of integers, write down on a piece of paper how you would implement this function and read it back to me. Follow up questions included what is the complexity of your algorithm (O notation)? How would you extend it to do nthLargest element? |
answer: My solution was to sort the list in descending order and quickly traverse the list for the second largest integer. Complexity would be the time it would take to sort the list. |
answer: linear solution if you track highest and secondHighest with integer variables |
question :
what is relative path? write a program to convert relative path to absolute path. |
answer: convert /usr/./local/../../bin/./../var/./log/ the absolute path for this is /var/log/ I had been asked to write a shell script to find it. |
answer: readlink -m "relative path"Example., readlink -m ..Will give the absolute path of the parent directory |
answer: readlink doesn’t accept any parameter "-m" |
answer: #!/bin/shmyPath=’/usr/./local/../../bin/./../var/./log/’cd $myPathnewPath=`pwd`echo $newPath |
question :
what is the difference between Java and C++ |
answer: garbage collection, multiple inheritance etc |
answer: portable binarydeclared exceptionsuniversal multi threading supportuniversal integer sizeuniversal io library |
Implement a function ion2e() that takes a string as a parameter. If the string ends with
‘ion’ it returns the initial part of the string (before the ‘ion’) followed by an ‘e’ with no
extra spaces. If the string does not end with ‘ion’, including the circumstance in which the
string contains ‘ion’ as a substring, it returns the original string.