You are on page 1of 14

Questions..

1) You are given a convex polygon and an additional point. You know the x and y coordinates of all vertices of the polygon and the point. Find if the point is one of the vertices of the polygon in O(log N) time. Still thinking... 2) You are given an array of N numbers and a integer x. You have to find the pairs whose sum is equal to x in n log (n) time. Ans2. Am giving you the pseudo code First sort the array of N numbers ---> O(n log(n)) Now find distinct numbers in the array and also store the frequency of each distinct number in a separate array. This can be done in one pass over the sorted array and using two more arrays. So if sorted array was -1,-1,0,0,0,1,3,4,4 the array with distinct numbers is -1,0,1,3,4 and corresponding frequency array is 2,3,1,1,2. --> O(n) Let these be named A[] and B[]. count = 0 For each number y in A[] starting from i = 1 ---> O(n) Binary Search for number (x-y) in array A ---> O(log(n)) If present, then we have at least one pair, let index of (x-y) be j if (A[i] != A[j]) count = count + B[i]*B[j] ---> O(1) else count = count + (B[j]-1)*(B[j])/2 set B[j] = 0 ( so that these pairs are not counted again )

3) If i < j and A[i] > A[j], the pair (i, j) is called an inversion. Find the inversions in an array of N numbers. 4) There is an integer K. You are allowed to add to K any of its divisors not equal to 1 and K. The same operation can be applied to the resulting number and so on. The goal is to: Given integers N and M, return the minimal number of the described operations necessary to transform N into M. Return -1 if M can't be obtained from N. For example, notice that starting from the number 4, we can reach any composite number by applying several such operations. The number 24 can be reached starting from 4 using five operations: 4->6->8->12->18->24 Ans. Starting from N, do BFS search for M. Termination condition will be whenever K becomes larger than M, return queue <int> q1; // stores each K queue <int> q2; // stores distance of each K from N q1.push(N); q2.push(0); while (!q1.empty()) { int K = q1.front();

int c = q2.front(); q1.pop(); q2.pop(); if (K == M) return c; if (K > M) continue; for (int i = 2; i <= sqrt(K); i++) { if (K % i == 0) { q1.push(K+i); q2.push(c+1); if (K/i != i) { q1.push(K+K/i); q2.push(c+1); } } } } return -1; To further optimize the algo, we can create an array telling if a number is prime or not. Each time K is a prime, then simply pop it from queue.

MS Interview Questions (Vaibhav) (5-8)

5) Convert a string to floating point and round off to two decimal places. float atof (char *p) { float I = 0.0; float F = 1.0; while (*p) { if (*p == .) { p++; if (*p == 0) return 0; // no digit after decimal int places = 1; while (*p) { if (places == 3) { if (6 <= *p && *p <= 9) I++; break; } if (*p == .) return 0; // more than one decimal returns 0 else if (0 <= *p && *p <= 9) { I = I*10.0 + (*p-0); F *= 10.0; } else return 0; // non-numeric character found places++; p++; }

if (places < 2) { I *= 10; F++; } return I/F; } else if (0 <= *p && *p <= 9) { I = I*10.0 + (*p-0); } else { // some non-numeric character return 0; } p++; } return I; } 6) Write a int MyDivision(int a, int b) which divides a/b. This seems to be all bit manipulations... Really difficult... I found a code on net : http:// www.bearcave.com/software/divide.c 7) Write a function to find (given 2 strings) whether one string is a substring of the other. // currently using a naive O(mn) algorithm // most efficient by KMP or even better by suffix tree int find (char *s, char *t) { // finds if t is a substring of s // returns -1 if not, else returns index of first occurence of t in s if (strlen(t) == 0) return 0; // null string can always be found at 1st index of s int i,j; for (i = 0; s[i]; i++) { if (s[i] == t[0]) { for (j = i; s[j] && t[j-i]; j++) if (s[j] != t[j-i]) break; if (!t[j-i]) return i; } } return -1; } 8) Write a program to find the smallest angle between the hour and min hands of a clock (You have the input as hh:mm)

9) Write a C program to implement a Generic Linked List. 10) How do you reverse a linked list without using any C pointers?

} 15) Compare two binary trees whether they are same or not? 16) Write a function to change a hexadecimal number to integer(htoi) ? 17) You have N computers [Ca, Cb] means a is connected to b and this connectivity is symmetric and transitive. Write a program which checks that all computers are interconnected and talk to each other? 18) Binary search tree is given. Find the kth smallest element? 19) Divide a number by 3 without using any %, *, / operators. You can use atoi() function. 20) Find no. of trailing zeros in factorial(100)? int two = 0; int five = 0; void primeFactorize (int n) { for (int i = 2; i * i <= n; i++) { if (n % i == 0) { if (i == 2 || i == 5) { int c = 0; while (n % i == 0) { n /= i; c++; } if (i == 2) two += c; else if (i == 5) five += c; } else { while (n % i == 0) n /= i; } } } if (n == 2) two++; if (n == 5) five++; } int trailing_zero (int n) { two = five = 0; for (int i = 2; i <= n; i++) primeFactorize(i); return min(two,five); } 21) You are given a large array X of integers [both positive and negative] and you need to find the maximum sum found in any contiguous sub array of x] standard dp solution

22) What is Little Endian and Big Endian?? How can i determine whether a machine's byte order is big endian or little endian?? Little endian stores the low order byte first, while big endian stores the high order byte first. void main() { short i = 1; char *ptr = (char*)&i; if(*ptr == 0) printf("big endian"); else printf("little endian"); } 23) Write a C code to check whether an integer is a power of 2 or not in a single line. [(num & num - 1)] if (n & (n-1) == 0) return true; else return false; 24) You are given two eggs. You have access to a 100 storey building. The eggs can break after falling from the first floor or may not break even after falling from the 100th floor. Both eggs are identical, you need to find out the highest floor from where the eggs can be dropped and yet not break. a binary search solution first check from the 50th floor, if breaks, then check 25th floor else check 75th floor and so on.. 25) On an empty chessboard, a horse starts from a point [say location (x, y)] and it starts moving randomly but once it moves out of board, it cannot come inside. So what is the probability that it stays on the board after N steps. double nr = 0, dr = 0; int dx[] = {1,1,-1,-1,2,2,-2,2}; int dy[] = {2,-2,2,-2,1,-1,1,-1}; void move (int x, int y, int step) { if (step == 0) { if (0 <= x && x < 8 && 0 <= y && y < 7) nr++; dr++; return; } for (int i = 0; i < 8; i++) { move(x+dx[i],y+dy[i],step-1); } }

return nr/dr; 26) What is the space complexity of Quicksort algorithm? O(n) 27) You are given a biased coin. Find an unbiased decision out of it. 28) Three strings A, B, C are given. Check whether the 3rd string is interleaved from the first two. A = "abcd" B = "xyz" C = "axbcyzd" Answer = "yes" need to check if same number of characters and same characters are present in C. 29) Algorithm for finding the longest palindrome in a string. keep shifting the centre of palindrome from 1 to n-1 and check for the largest palindrome that can be made at that centre. Takes O(n^2) int longest_palindrome (char *p) { int dp[strlen(p)]; memset(dp,1,sizeof(dp)); for (int i = 1; i < strlen(p)-1; i++) { for (int j = i-1, k = i+1; j >= 0 && k < strlen(p); j--,k++) { if (p[j] == p[k]) dp[i] += 2; else break; } } int max = 0; for (int i = 0; i < strlen(p); i++) max = max(dp[i],max); return max; } 30) Given a dart board of radius 'r', if a dart is thrown on the board which always fall inside assuming uniform distribution, find the expected distance from the center for where the dart lands. 31) You have a linked list of unknown length 'n'. There is a element which is repeated more than n/2 number of times. Find the element using constant extra space and one pass over the list. 32) You are shrunk to the height of a nickel and your mass is proportionally reduced so as to maintain your original density. You are then thrown into an empty glass blender. The blades will start moving in 60 seconds. What do you do? 33) You have a given binary search tree. Using this tree make a sorted doubly linked list using the elements of the tree. 34) You have N steps to get down. You have two options: (a) either you come one step down (nth to (n-1)th), (b) or you directly jump to the 3rd step leaving one step in between (say from nth to (n-2)th). Find the total possible ways in which one can get down.

35) Write an efficient function in C to delete some characters from a string in O(n) without additional space. Ashish Garg, remove 's', 'a' --> hih grg

Qualcomm

50) Find the sum of the path that equals 'X' in a binary tree.

51) Find the kth largest number in an array. 52) How would you test a distributed system 53) How would find the largest prefix in a group of strings. Convert the algorithm to find the largest substring in a group of strings 54) Given a pre-order sequence of numbers, find a unique BST. 55) Given a dictionary of four letter words, find the shortest sequence of words leading from one word to another. ex. CAT -> COT -> DOT -> DOG 56) Given an integer array A, derive an array that holds at index i, the product of all the numbers in A except A[i]. 57) Given a billion search queries coming in through the day, find the ones that are unique. Consider storage space complexity also. 58) Given an integer array, reshuffle the contents such that any repeating integers are K distance from each other.

Amazon
59 ) Linked List: Traversal of a node in singly & doubly linked list 60) Array: sorting of arrays / sorting algos (Heap sort, Merge sort) 61) Stack & Queue 62) Concepts like LIFO & FIFO 63) Complexity of algorithms 64) Problem Solving: A scenario will given to you & you need to come up with solution in the form of code. 65) Find the largest integer in an array 66) How will you find out the difference between Binary Trees and Binary Search Trees? They wanted to know how I will implement it? Complexity? 67) Write code to find the kth largest element in a Binary Search Tree. I wrote the c++ function, and then was debugging it for various edge conditions.. 68) Find the first occurrence of an integer in an array. The best and worst cases. Write the code. I explained binary search, and wrote the function. 69) Find the width of a binary tree. I wrote the function for it. 70) He asked if I had built and tested a system end-to-end, 71) Tell some details about multi-threading programming. What is semaphore? Diff between thread and process etc etc

72) How search engine make index of documents? What data structure should you use? How do u index a database for range finding query. Etc etc.... Inverted map which maps tokens (strings) with the doc_ids in which they occur. A trie tree can be used for this purpose. Inserting all tokens and the end node storing doc_set. 73) Write a code to make canonical form a directory listing. 74) Design and implement Least Recently Used based hash - discussion on data structure to use, algo, unit test, etc 75) Select k smallest integer from n integer where n is very large and k is very small. 76) OS level Q: diff between user level thread vs kernel level thread, page replacement algo, etc. 77) Find the first common ancestor of two given nodes in a binay search tree. 78) using a function int random(); //returns 0 or 1 implement a function int rnd(int a , int b ); // which returns a random value between 'a' and 'b' 79) Difference between multi-processing and multi-threading.. and then he went into kernel level threads and user level threads... > what would i chose for implementing a webserver (multi processing, or multi threading (user level or kernel level) and why?) 80) Design/architect a web portal for a library in a college: >> What a re the types of users.. And functions that should be exposed to them >> The overall appplication structure >> The database schema (with the details of each table)\ 81) Given a sentence reverse individual words. Write code and read out. "This is Amazon" -> "sihT si nozamA" 82) Given array of n integers and an integer x, find whether there exist two elements in the array whose sum equals x. 83) Design Least Recently Used cache 84) Design chess game and send the class diagram to the given email address in an hour 85) Write a code snippet to simulate memory leak 86) Find whether a substring exists in the given string. bool substring(const char *string, const char *substr); 87) Write a code to determine if a given binary tree is a binary search tree or not. Binary search tree is a tree in which all elements to the left of a node are smaller and all elements to the right are bigger. 88) There is an external array of integers on which you can perform the following operations in O(1) time. 1. get(int i) - returns the value at the index 'i' in the external array. 2. reverse( int i, int j) - returns the reverse of the array between index positions i and j (including i and

j). example for reverse: consider an array {1,2,3,4,5}. reverse(0,2) will return {3,2,1,4,5} and reverse(1,4) will return {1,5,4,3,2}. 89) Write a code to sort the external array. Mention the time and space complexity for your code. 90) Implement memcopy ( C library function) covering all edge conditions. The signature was void memcopy( char *str, int src, int des, int num_elements); 91) To find the Least common ancestor of 2 given nodes in Binary Tree ( Note: Its a Binary Tree & not a BST) 92) Find the anagrams of a string. 93) Data structure being used while implementing dictionary. 94) To find largest palindrome in a given series of number in an optimized manner { eg:I/P: 1345334433677699897 334433 95) Given a string. Fiind out the length of maximum length palindrome in that string. 96) Given two strings s1 and s2. Remove all the characters of string s1 from s2. 97) Given a stack of integers. Allowed operations -> push and pop. Define a function getmax() in O(1). 98) Iterative preorder traversal of tree. 99) Level order traversel of a tree. 100) Given an array of million integers. Find out the smallest k elemenmt. Restrictions: Only a main memory for storing k integers + for some temporary variables is available. 101) Given a 2D m x n array of characters. Find out all the possible words that can be made from that array. AMAZON::

o/p :

Here you go Phone screen 1- Tell us about yourself and your work - Tell us how you handle conflict in priorities - How do you handle ambiguity in scope of projects - What tools do you use ? Which one do you like and why? Which one dont you like? - What was a failure of yours and what was the biggest learning from it Phone screen 2- Give an algorithm for an elevator problem. - Traverse linked list, delete a pointer, identify circular linked lists, find common parent in a tree - Queries - simple query using group by on emp table and salary table