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

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

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; 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 leftSums = a; 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 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