Skip to main content

Posts

Showing posts with the label Google Interview

Scaling application

 We all wish that our application used by maximum people on Earth. To make sure we have the right scalable application, please follow below guidelines  1. Load balancing at all level of application i.e. web server, application server and DB server 2. Remote caching to be enabled for a fast response.  3. Load balancer will equally distribute the traffic to existing servers, what if enough capacity is not enough. We should have a mechanism to increase the server capacity (esp horizontally ).  All the cloud service provider has provision for autoscaling, so do Kubernetes.  Use them.  4. Most of the NoSQL DB comes with good support for horizontal scalability. So if you chosse NoSQL you can easily scale them. But if your application requires RDBMS (SQL) then plan should be with sharding in place.  5. Server should be stateless. Any server should be able to serve an incoming request. No local storage, no IP binding. Having said newly added server will start ...

Consistent Hashing

I will try to explain consistent hashing with a real world example. Let's assume I have a restaurant with 60 tables and 5 servers (waiter). Each server is given an equal number of tables to serve. Now let's assume we have addition of a new server (waiter), so his addition will be marked in the circle and he will be receiving tables from the previous server to his distance only. Check the attached example. Assume a server (waiter) has left the organisation and we have only 4 servers now. Server3 has left the restaurant, so his table will be assigned to server 4. I am sure you have noticed the load is not equally distributed. But to make the system less prone to addition/removal we just rotate in clockwise and assign range from the previous server to present server.  To make sure load is balanced or optimally balanced we need to use virtual nodes. Check links here: http://tom-e-white.com/2007/11/consistent-hashing.html https://www.toptal.com/big-data/...

3Sum

given 3 arrays, array a, array b, array c. find all pairs where a[i] + b[j] = c[k] a, b , c are sorted. A matching quadratic solution is available on wiki, please visit this link: http://en.wikipedia.org/wiki/3SUM

Missing integer(s) in the array

You have given two array e.g. A[] and B[]. Difference between two arrays that A[] have two additional numbers than B[]. both the array is randomized and not in order.   We have to find out both the number in array A[] in most effcient way. Dont try to sort and compare as  time complexity is nlogn. Need a faster solution. Assume We have elements in array A are a0, a1, a2, ................an And Array B are b0, b1, b2, b3.....................bn. Now as per above condition all the elements of B  already  present with A. So we can represent like A[] = B[]+ai+aj where ai and aj is the missing number. Step1: XOR all the elements for A[] XOR B[]. So result will ai XOR aj as remaining elements will be removed by XOR.  Step2: Now take any bit set in above result. Assume we have result in variable result. Any bit set in result will be either set in ai or aj. Can not be in both the variable.  Assume set bit is 5th bit. A...

Permutations Sum(xi)

You have given "k" dice. How many way you can get a sum "S" and yes you have to throw all the dice. Write program for this. Its same permutations program...but we have to try with all the six S(1,2,3,4,5,6) possibilities for a dice. Exit condition will be If all the dice run out. SumP(dice,sum) = SumP(dice-1,sum-i)+i (from S).

All possiblities of balanced Parenthesis

print all balanced parenthesis of size "n". [ex:- for 1: (), for 2: ()(), (()); like this] Printing balance paranthesis, need dynamically updating your options. Such as initially only openeing brace can be choosen and closing braces are not present. You choose one opening brace and add into your result, this will decrease the number of opening brace but increase the closing brace count by one. In normal permuations program, we try with every element in set with every other element. So, here are only two choices given one opening brance and closing brace with n numbers. So, everytime we try to choose, we check for the opening brace count available and closing brance count available. I am posting my program here, #include using namespace std; static int permcnt; void print( char out[], int cnt) { //Print all the index from 0 to cnt-1 of out permcnt++; } void generate ( char in[], int i, int opara,int cpara) { int j; if ( opara == 0 && cpara == 0) { ...

Smallest Snip of givem M words

Yor are given occurrences of 3 words (say, "bangalore", "hyderabad", "google") in a file. bangalore: 100, 130, 157, ... hyderabad: 80, 145, 180, .... google: 60, 139, 197, ... [Note: occurrences are given in sorted order.] Now, you need to find the "smallest snip" containing all these three words. [In this case: 130("hyderabad"), 139("google"), 145("bangalore") - 15 is snippet size]. Can you generalize this for m words and length of occurrences is n. Algorithm: Take first element from all list and put in a array. minsnip = INT_MAX; while any of list have element. do currentsnip = max in array - min in array; if currentsnip minsnip = currentsnip; delete the min element from array. Get second element fron deleted list. done

Median of stream of numbers

Problem: Design a data structure which can perform most efficiently insert and median. My Solution: struct node { int number; node *left; node *right; int leftTreeNode; }; struct header { int totalNodes; Int valid; int median; node *root; } myhead ; //myhead ......thats where it will start. void initialize() { valid = 0, median = 0, root =NULL, totalNodes =0; } void AddNode ( int n ) { myhead.totalNodes++; myhead.valid = 0; node *prev = NULL; node *temp = myhead->root; while ( temp != NULL ) { if ( n number ) { prev = temp; temp->leftTreeNodes +=1; temp = temp->left; } else { prev = temp; temp = temp->right; } } if ( prev != NULL ) { if ( n number ) prev->left = createNode(n) else prev->right = createNode(n); } else myhead->root = createNod...

Blood Relation

There are N persons in a country. N is very big in millions. Design a efficient data structure and algorithm to find out whether there is blood relations between given two person or say they have a common ancestor . My solution: Used a map //UID by Nandan Nilekani :) struct person { struct person *father; struct person *mother; list child; //However may not be needed for this problem string name ...i.e. //Add more } struct person * findAncestor ( struct person *a, struct person *b) { Take first node in stack. While ( stack is not null ) { Mark Node. Push Its ancestor in stack; } Take second node in stack. while ( stack is not null ) { If marked return Node, push ancestor in stack. } return NULL; } It has a drawback, i need to clear the flagged node before i apply the search algorithm again. But till now the best i know.

Maximum Gain Stock Market

Given an array which have samples of stock price at different timestamps. You have to find best timings when we can buy and sell and make maximum benifit by it. No need to say u can sell only after you buy. Its simple DP problem, just need to form a equation MaxGain(i) = Max(MaxGain(i-1), DIff(i,min)) Min is the index of element having min value till now. Diff will return the value(i)-value(min). Hope its clear.

Car Parking Problem

There is n parking slots and n-1 car already parked. Lets say car parked with initial arrangement and we want to make the car to be parked to some other arrangement. Lets say n = 5, inital = free, 3, 4, 1, 2 desired = 1, free, 2, 4 ,3 Give an algorithm with minimum steps needed to get desired arrangement. Told by one of my friend and after a lot of search i really got a nice solution. I will post solution in comment part

Median of Five Numbers

U have 5 NOs , X1,X2,X3,X4,X5 With minimum no. of comparisons we have to find a median. SWAP(X,Y) function is available to u . I have a answer of six comparisons and eight swaps....wait for people to find out by themselves.

Google Questions (Plenty coming )

Given n distinct points prove that for all k,0 divide points into n-k and k points by drawing a line segment.... Proof given on a site There are n points, so max n(n-1)/2 different directions of the line segments joining two points among these n points. Now draw any line which has direction different than above at most n(n-1)/2 values. By choosing a different direction you are making sure that no two points can lie on the line. Now you can 'drag' the line as much as you want and get as many points on it's one of the sides as you want.