Software Engineering Interview Questions in San Jose, CA | Glassdoor

# Software Engineering Interview Questions in San Jose, CA

6,130

Software engineering interview questions shared by candidates

## Top Interview Questions

Sort: RelevancePopular Date

Apr 24, 2011

Apr 24, 2011

Aug 9, 2009

### Software Engineer at Facebook was asked...

Sep 20, 2011
 print out all prime numbers in a given string. abc2134kd31 -> 2, 13, 3, 310 AnswerseasyCode in C# - verified working: static void PrintPrimes(string str) { int i; string lastNum = null; foreach (char c in str) { if (Int32.TryParse(c.ToString(), out i)) { lastNum = lastNum += i.ToString(); int concatNum = Int32.Parse(lastNum); // Iterate through all nums for (int ix = 0; ix < lastNum.Length; ix++) { string currNumStr = lastNum.Substring(ix, (lastNum.Length - ix)); int currNum = Int32.Parse(currNumStr); // Print out if prime if (isPrime(currNum)) { Console.WriteLine(currNum); } } } else { lastNum = null; } } } static bool isPrime(int x) { for (int i = 2; i <= Math.Sqrt(x); i++) { if (x % i == 0) return false; } return true; }btw, correct answer is not "2, 13, 3, 3" but "2, 13, 3, 3, 31"Show More ResponsesHere is the answer bool isPrime(int num) { for (int i=2;i '9' || currentChar < '0') { return false; } int currentDigit = currentChar - '0'; num = num*(current+1); num += currentDigit; } return true; } void PrintPrimes(char* text, int length) { if (length == 0) { return; } int currentIndex; int currentLength; while (currentIndex < length) { char* temp = new char[currentLength+1]; strcpy(temp, text+currentIndex, currentLength); int num; if (ConverToNum(temp, currentLength, &num)) { if (isPrime(num)) { Console.WriteLine(num); } currentLength++; } else { // couldn't convert to a number therefore we hit a non-integer currentIndex = currentIndex + currentLength + 1; currentLength = 0; } } }public class Prime { /** * @param args */ public static boolean isInteger(char c) { try { Integer.parseInt(String.valueOf(c)); return true; } catch (NumberFormatException nfe) {} return false; } public static void main(String[] args) { // TODO Auto-generated method stub String str="abc2134d31"; findprime(str); } static boolean isPrime(int x) { for (int i = 2; i <= Math.sqrt(x); i++) { if (x % i == 0) return false; } return true; } private static void findprime(String str) { // TODO Auto-generated method stub for(int i=0;i\$str = "35713m2m16mmm16mm97m47"; for(\$i=0;\$i<=strlen(\$str);\$i++) { if (!is_numeric(substr(\$str,\$i,1))) { continue; } for(\$j=\$i+1;\$j<=strlen(\$str);\$j++) { if (is_prime((int)substr(\$str,\$i,\$j-\$i))) { print substr(\$str,\$i,\$j-\$i).","; \$i=\$j-1;break; } if (!is_numeric(substr(\$str,\$i,\$j-\$i))) { \$i=\$j-1;break; } } } function is_prime(\$i) { if(\$i == 2) return true; if(\$i % 2 != 1 || \$i == 1) return false; \$d = 3; \$x = sqrt(\$i); while (\$i % \$d != 0 && \$d < \$x) \$d += 2; return ((\$i % \$d == 0 && \$i != \$d) * 1) == 0 ? true : false; }Vishal's code has a small bug, if you input test61test , it checks if 6 is prime, if it is it does the checknext function, it should implement checknext regardless that number being prime or not. public class Prime { //Take any string and print all the prime numbers in it /** * @param args */ public static boolean isInteger(char c) { try { Integer.parseInt(String.valueOf(c)); return true; } catch (NumberFormatException nfe) {} return false; } public static void main(String[] args) { // TODO Auto-generated method stub String str="ibby37primete61s43"; findprime(str); } static boolean isPrime(int x) { for (int i = 2; i <= Math.sqrt(x); i++) { if (x % i == 0) return false; } return true; } private static void findprime(String str) { // TODO Auto-generated method stub for(int i=0;ijavascript version: var isPrime = function (n) { if (n === 2) return true; if (n < 2 || n % 2 === 0) return false; for (var d = 3, t = n; d < t; t = ~~(n/d), d += 2) { if (n % d === 0) return false; } return true; }; var printPrimes = function (s) { var i, j, k, c, d, result = []; for (i = 0, j = s.length; i < j; i++) { c = s.charAt(i); if (!isNaN(c)) { if (isPrime(~~c)) result.push(c); for (k = i + 1; k < j; k++) { d = s.charAt(k); if (!isNaN(k)) { c += s.charAt(k); if (isPrime(~~c)) result.push(c); } else { break; } } } } return result; }java version public boolean isPrime(int n){ if(n = 0 && c - '0' findPrimes(String str){ char[] chars = str.toCharArray(); List nums = new LinkedList(); for(int i = 0; i < chars.length; i++){ String temp = ""; for(int k = i; k < chars.length; k++){ char x = chars[k]; if(isNum(x)){ temp += x + ""; if(isPrime(Integer.parseInt(temp))){ nums.add(temp); } } else break; } } return nums; }A recursive C++ version: // borrowed from http://en.wikipedia.org/wiki/Primality_test#Java_implementation bool isPrime(unsigned x) { // x in [2, 3] if (x 1); // x divisible by 2 or 3 if (!(x%2) || !(x%3)) return false; // chug along: // if x is not prime, x = a * b, where either a or b < int(sqrt(x)) // it's enough to check until i^2 <= x for (int i = 5; i*i <= x; i += 6) if (!(x%i) || !(x%(i+2))) // divisible by i or (i+2) return false; return true; } bool isNumber(char c) { return ('0' <= c && c <= '9'); } void printPrimes(const string& str, string temp, int i) { if (str.empty()) return; if (temp.size() == str.size()) { printPrimes(str.substr(1), "", 0); return; } temp += str[i]; if (isPrime(atoi(temp.c_str()))) printf("%s\n", temp.c_str()); printPrimes(str, temp, i+1); } void printPrimes(string str) { for (int i = 0, j = 0; j < str.size(); ) { // skip non-numerical chars while (!isNumber(str[++i])); // continue while numerical chars j = i; while (isNumber(str[j++])); printPrimes(str.substr(i, j-i), "", 0); i = j; } }

Dec 16, 2010

### Contract Ruby On Rails Software Engineer at LinkedIn was asked...

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)}

Feb 9, 2011

### Software Engineer at Google was asked...

Mar 17, 2012
 Find the balance point in an array. (The index where the sum of the elements to the left it is the same as the sum of the elements to the right of it.)7 Answerspublic class Solution { public static int solve(int[] arr){ int mid = arr.length/2; int sumLeft=0; int sumRight=0; int index = -1; boolean flagLeft= false; boolean flagRight= false; for(int i=0;isumRight && !flagLeft){ sumRight+=arr[mid]; sumLeft-=arr[mid-1]; mid--; flagRight=true; } else if(sumLeft==sumRight){ index=mid; break; } else{ return -1; } } return index; } public static void main(String args[]){ int [] temp = {9,5,4,1,3,10,5}; int t = solve(temp); System.out.println("Index: "+t); //Output the index } }more complicated than it needs to be.or: long sumLeft = arr[0]; long sumRight = arr[arr.length-1]; int i=1, j = arr.length-2; for (; i sumRight) { sumRight += arr[j--]; }else { sumLeft += arr[i++]; sumRight += arr[j--]; } } return i;Show More ResponsesThe 3rd solution is brilliant but it is only applicable to arrays containing only non-negative values. The solution to solve the problems regardless of value signs but using addition O(n) memory: public static int BalanceImprove(int[] a) { //as we discussed we need two extra arrays to store the sums from left to right and from right to left int[] leftSums = new int[a.length]; int[] rightSums = new int[a.length]; //now we compute sums for leftSums, but as each sum is depending on previous sum, we need assign the 1st sum to a[0] leftSums[0] = a[0]; for(int i=1; i=0; i--) rightSums[i] = rightSums[i+1]+a[i]; //now compare each value in left and right sum arrays to find match for(int i=0; iBy adding one more array and do DP, your sum from left to right and right to left arrays will save more computations. But the most easy case should be one pass do a sum, second pass use one tmp to calculate sum_left, if its' half of sum-a[i], then you get it.- Find total sum of all elements in the array. - Now iterate to array again and keep adding element value to sum1 - keep doing it and subtract the value of the element from total sum - loop this untill we reach a point i where sum1 = sum - element[i]. - i is the index of that element which divides the array into two similar parts - Complexity O(N)def balance_point(arr): s1, s2 = 0, sum(arr)-arr[0] for i in range(len(arr)-2): if s1 == s2: return s1 s1 += arr[i] s2 -= arr[i+1] print balance_point([10, -2, 1, 3, 4, 2])

### Software Engineer In Test at Google was asked...

Jan 15, 2010
 You are a parking lot attendant in a lot that has one open spot, and you want to move the cars from their original positions into a new arrangement. Create a program that will print out instructions on how to move the cars most efficiently. 7 AnswersThe problem is not too difficult, what you have to do is find the empty spot, then look in the desired arrangement for what car should be in that spot, and move that car there. Repeat until complete.Does this really work? If I the empty spot is expected to be the same, but the positions of two (or more) cars are switched, how to rearrange it without a complete search?It's the Tower of Hanoi Problem.Show More ResponsesSo there are actually 2 empty spots then or is there a way to 'stack' cars I don't know of?The parking lot problem has nothing to do with Tower of Hanoi, which requires O(2^n -1). This problem, however, can be solved in O(n) - that's because all you need to do is to perform (0 or more) rotations using the empty parking spot.Here is a C# implementation, using generics and .NET 4.0 Tuple: IEnumerable> RearrangeCars( TCar emptyCarMarker, IDictionary initial, IDictionary desired) { // reverse the lookup: car -> spot Dictionary pending = initial.ToDictionary(p => p.Value, p => p.Key); // remove emptySpot from lookup TSpot emptySpot = pending[emptyCarMarker]; pending.Remove(emptyCarMarker); while (pending.Any()) { // check if the empty spot is where is should be if (desired[emptySpot].Equals(emptyCarMarker)) { while (true) { // pick a car (any car would do) var carToMove = pending.First(); // check if this car is already in its desired position if (desired[carToMove.Value].Equals(carToMove.Key)) { // remove from pending, no moving is necessary pending.Remove(carToMove.Key); if (pending.Any() == false) yield break; } else { yield return new Tuple(carToMove.Key, carToMove.Value, emptySpot); // move the car TSpot newSpot = emptySpot; emptySpot = carToMove.Value; pending[carToMove.Key] = newSpot; break; } } } // move the car into its desired spot var car = desired[emptySpot]; var newEmptySpot = pending[car]; yield return new Tuple(car, newEmptySpot, emptySpot); emptySpot = newEmptySpot; pending.Remove(car); } } Note that there is a while-loop inside another while-loop. However, the complexity is still O(n) since at every iteration of internal or external loop, the "pending" map is reduced by one element. Below are some examples (emptyCarMarker == ""). EXAMPLE 1: Input: initial == { "", "B", "A"} desired == { "", "A", "B"} Output: (B, 1, 0) // move car B from spot #1 to #0 (A, 2, 1) // move car A from spot #2 to #1 (B, 0, 2) // move car B from spot #0 to #2 EXAMPLE 2: Input: initial == { "", "B", "A", "D", "C" } desired == { "A", "B", "", "C", "D" } Output: (A, 2, 0) (D, 3, 2) (C, 4, 3) (D, 2, 4)Here is a Java Implementation, using Google's guava library for the BiMap. It takes O(n) to first create the BiMap and O(n) to move the cars, total O(2n), i.e. O(n) time complexity. import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import java.util.Map; import java.util.Set; class ParkingAttendant { static class ParkingConfiguration { static final Integer EMPTY = -1; Integer moves = 0; BiMap conf, i_conf; static ParkingConfiguration getInstance(int[] conf){ return new ParkingConfiguration(conf); } private ParkingConfiguration(int[] conf){ this.conf = arrayToMap(conf); this.i_conf = this.conf.inverse(); } BiMap arrayToMap(int[] arr){ BiMap m = HashBiMap.create(arr.length); for(int i=0;i> entrySet(){ return conf.entrySet(); } } static void moveCars(ParkingConfiguration from, int[] to){ for(int pos=0; pos e : p.entrySet()){ int pos = e.getKey(); int car = e.getValue(); System.out.format("%1\$s, ", ParkingConfiguration.EMPTY.equals(car)?"_":car); } System.out.println("]"); } static void printCars(int[] p){ System.out.print("["); for(int pos=0; pos

### Software Engineer at Google was asked...

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[0][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[0] = a[0]; 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[0][n-1]; } public static void main(String[] args) { int[] a = {1,9,5,3,6,2}; System.out.println(solve(a,0)); } }
3140 of 6,130 Interview Questions