Algorithm Interview Questions | Glassdoor

# Algorithm Interview Questions

768

interview questions shared by candidates

## Algorithm Interview Questions

Sort: RelevancePopular Date

Apr 16, 2013

Apr 24, 2011

Apr 24, 2011

Jan 27, 2012
 Describe a routine which returns the set of integers in {1..100} divisible without remainder by 3 but not by 9.12 AnswersI'm assuming the question wants us to find integers that are divisible by 3 but not by 9. This can be easily obtained using a mod function inside the following if statement: if(number % 3 == 0 && number % 9 != 0) Here is a short program I wrote in c++ to show how to solve this problem. Instead of returning the set of integer, I just printed them out on the screen: #include #include using namespace std; int main(int argc, char** argv) { int i = 0; vector list; vector::iterator it; for(i = 1; i <= 100; i++) { if(i%3 == 0 && i%9 != 0) { list.push_back(i); } } for(it = list.begin(); it != list.end(); it++) { cout << *it << endl; } return 0; } If I missed anything, please let me know. Happy coding and problem solving!That'll certainly work, Tyler, but the OP indicated he was interviewing for a Ruby On Rails - not C++ - gig.put those integers into an array, pick every third element, out of which discard every third element.Show More Responsespython [x for x in range(0,100) if x % 3 == 0 and x % 9 != 0]1) start from number = 3 Loop while(number <= 100) 2) display number 3) number = number+3, display number 4) number = number+6 Loop(1..100).map { |i| (i % 3).zero? && !(i % 9).zero? ? i : nil }.compact(1..100).select { |x| x%3 == 0 && x%9 != 0matt has the best answerA variation on Matt's answer: (1..100).select { |n| n % 3 == 0 }.reject { |n| n % 9 == 0 }The requirement doesn't say if the input has to be a Range. If it doesn't have to be, then we don't need to traverse each element but to simply calculate it. def get_nums_by_3_not_by_9(max) arr = [] x = max.to_i / 3 x.times do |i| next if i % 3 == 0 arr << i * 3 end return arr end(1..100).select do |n| n%3 ==0 and n%9 != 0 end(1..100).to_a.delete_if{|x| !(x%3==0 && x%9>0)} or (1..100).to_a.select{|x| x%3==0 && x%9>0} or (1..100).to_a.map{|x| x%3==0 && x%9>0 ? x : nil}.compact or (1..100).to_a.reject{|x| !(x%3==0 && x%9>0)}

### Software Engineer at Amazon was asked...

May 12, 2010
 Given a list of integers, some of which may be negative, extract the pair that sums to the largest number.8 AnswersThe 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.you can get the largest two number in O(n), right? sum those two numbers up.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.Show More ResponsesKeep 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 S This is the subset problem. This is O( n ), but requires O( S ) space.@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.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 sell 2. Have two pointers - one at the end and the other at the beginning 3.a. If the sum is less than S increment the one in the beginning 3.b. If the sum is greater than S decrement the one at the end 3.c If the sum is S - you are done 3.d If the two pointers have met or crossed over - you are doneAmazon really loves dynamic programming eh? I've come across many interview questions with the knapsack and coin-change problems#define SIZE 3 int tab[SIZE]; int sum; int max=-MAXINT; int sovi, sovj; for(i=0; i max) { max=sum+tab[j]; sovi=i; sovj=j; } } } printf("\n i: %d j:%d", sovi, sovj);

### Software Development Engineer at Amazon was asked...

Jan 14, 2010
 How would you find the pairs of numbers that added to some specific number in an array. 7 Answersi program in java..so i will talk from the arrayLists perspective. suppose we want to find out a+b = 123; for(int i=0; i2000 records.but below that, sorting and above operation is efficient. you must play with different possibilities.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 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 and iterate backwards from the previous last item ... keep going. This is at worst proportional to n/2, ie O(n).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).Show More ResponsesDuh - sorting is O(nlog n) ...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.sort the array (o(n(log(n)) and take two pointers at both the ends say p1 and p2 if p1+ p2 move the pointer p2 by 1 and add to check if (p1+p2) > n -> move the pointer p1 by 1 and add to check if (p1+p2) = n ->print the pair [traversal takes o(n)] finally thus can be done in o(n)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/2 Second array will contain all values > k/2 This 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).

### Software Engineer at Amazon was asked...

Dec 24, 2011

Aug 16, 2010
 There are n pots with different # gold coins in them. Two players play a game, where each player can select a pot at either ends. maximize the gold7 AnswersUse dynamic programming to solve the same. Could explain the logic, but again did not find the time to code it up.What does "maximize the gold" mean in this game? If it means to keep the heavier pots for the end of the game and keep the two sides balanced, then I think you need to sort the N pots and redistribute so that the heaviest is in the middle and the two sides are balanced. Since a pot can contain only a limited number of gold, I would use a count sort algorithm for an average time of O(N+k). When re-distributing, I would balance the two sides starting by the heaviest pot, according to the individual sides's weight. For example: 1, 4, 10, 2, 3, 4, 2 Counting sort: 1:. 2:.. 3:. 4:.. 5: 6: 7: 8: 9: 10:. Sorted list: 1, 2, 2, 3, 4, 4, 10 If K is odd, remember the heaviest = 10 Re-distributing by weights: 4, 3, 1 4, 2, 2 Final list: 1, 3, 4, 10, 4, 2, 2To maximize the gold means, each player wants to maximize the amount of gold the player gets by selection of one pot at a time (either leftmost or rightmost). Player 1 selects a pot, followed by player 2, followed by player 1 etc. How does the player select picking Left or right one ? Maximize gold means sum of the gold coins of all the pots selected by a player. I did not follow how sorting helpsShow More ResponsesHow about take differences and get the side that gives you a better gain. For example: 8 7 4 6 Take 6 Then take 7I think the idea is that each person takes turns choosing the currently leftmost or rightmost pot and tries to maximize the sum of all the pots they take. You can't be greedy because of situations like this: 10, 100, 10, 5 If you were greedy, you would take 10 first, and the other person would take 100. If you instead took 5, they would be forced to take one of the 10's, leaving the 100 available for you to take. The recursive idea here is minimax. The maximum I get from X to Y is the maximum of either the gold at X + what's left over when the other player takes from X+1 to Y, or the gold at Y + what's left over when the other player takes from X to Y-1. As an implementation note, we should keep track of the amount both players get over each interval. If the other player gets R gold, with T gold leftover for me, when choosing from the subrange X+1 to Y, then from the range X to Y, I can easily say that if I choose to take the gold from X, I get T + gold[X] gold, leaving R gold for the other person. This makes the code much simpler. Since each case is based only on subcases of a smaller length (e.g. from X to Y, which is length Y - X, only depends on X to Y-1 and X+1 to Y, both of length Y-X-1), we can build up the cases in order of length. C++ DP implementation would look something like this: pair dp[n][n]; for (int i = 0; i L = dp[i + 1][i + len]; pair R = dp[i][i + len - 1]; if (gold[i] + L.second > gold[i + len] + R.second) dp[i][i + len] = make_pair(gold[i] + L.second, L.first); else dp[i][i + len] = make_pair(gold[i + len] + R.second, R.first); } } The amount of gold I get is dp[n - 1].firstUse induction: Suppose that I know how to play best with N arbitrary pots. What's my best move with N+2 pots? Trivial cases: N=0 and N=1. With N+2 pots, I can chose L or R. After that my opponent chooses L or R. Then it's my turn again, but this time, with N pots, I know how to play, by induction hypothesis. So what's the best move? It's the one that maximizes the worst case scenario (that is, my opponent playing her best). What's the worst if I pick the left? It's the value of the left pot plus the minimum of two scenarios: 1. the opponent picks L and I do my best with what's left and 2. the opponent picks R and I do my best with what's left. I do the same calculation assuming that I take the right first. The best of the two worst scenarios maximizes my goal. Here's the code in C++: enum Move ( L, R, E }; // left, right, end of game Move BestMove(int const * left, int const * right, int & minGain) { if (left == right) // there's nothing left in between { minGain = 0; return E; } if (right - left == 1) // just one left { minGain = *left; return L; // arbitrary choice } // I take left, she takes right int xLL; BestMove(left + 2, right, xLL); // I take the left, she takes the right, or vice versa int xLR; BestMove(left + 1, right - 1, xLR); // I take the right, she takes the right int xRR; BestMove(left, right - 2, xRR); // my worst if I take left int wLeft = *left + std::min(xLL, xLR); // my worst if I take right int wRight = *(r-1) + std::min(xLR, xRR); // the better of the two minGain = std::max(wLeft, wRight); return (wLeft >= wRight)? L: R; } void main() { int pots[] = { 2, 4, 10, 2, 3, 1 }; int minGain; Move m = BestMove(a, a + 6, minGain); }Dynamic programming public class GoldPots { public static int max(int a, int b) { return a < b ? b : a; } public static int solve(int[] a, int player) { int n = a.length; int[][] m = new int[n][n]; int[] sums = new int[n]; sums = a; for(int i = 1; i < n; i++) { sums[i] = sums[i-1] + a[i]; } for(int i = 0; i < n; i++) { m[i][i] = a[i]; } int sumij; for(int k = 1; k < n - 1; k++) { for(int i = 0; i < n - k; i++) { for(int j = i + k; j < n; j++) { sumij = sums[j] - sums[i] + a[i]; m[i][j] = max(sumij - m[i + 1][j], sumij - m[i][j-1]); } } } return m[n-1]; } public static void main(String[] args) { int[] a = {1,9,5,3,6,2}; System.out.println(solve(a,0)); } }