Senior software developer Interview Questions in United States
senior software developer interview questions shared by candidates
Top Interview Questions
Senior Software Engineer at Google was asked...
Given an array of numbers, replace each number with the product of all the numbers in the array except the number itself *without* using division. 34 AnswersCreate a tree, where the leaf nodes are the initial values in the array. Given array A[1..n] create array B[1..n]= {1} // all elements =1 ; for (i=1; ij) B[i] *=A[j]; } } A=B; To husb: Your answer will work, but it's O(n^2) solution. Can you do better? Show more responses Am I missing something? It can't be this easy: given array[0..n] int total = 0; for(int i=0; i<=n; i++) { total += array[i]; } for(int i=0; i<=n; i++) { array[i] = total-array[i]; } Ah yes.. I was. The question is PRODUCT, not sum. That will teach me to read the question too fast ;) Create a tree, where the leaf nodes are the initial values in the array. Build the binary tree upwards with parent nodes the value of the PRODUCT of its child nodes. After the tree is built, each leaf node's value is replaced by the product of all the value of the "OTHER" child node on its path to root. The pseudo code is like this given int array[1...n] int level_size = n/2; while(level_size != 1){//build the tree int new_array[1...level_size]; for ( int i=0; i left = array[i*2]; (and also from child to parent) new_array[i] -> right = array[i*2+1] new_array[i] = new_array[i] -> right* new_array[i] -> left; (take the product) } array= new_array; level_size /=2; } for(int i=0; iparent; if( parent->left == node){//find the other node under the parent brother = parent->right; } else{ brother = parent->left; } p *= brother; node = parent; } return p; } btw, it's O(n*logn) It seems to me that for any number array[i], you're looking for PRODUCT(all array[j] where j i]) we can simply precompute these "running products" first from left-to-right, then right-to-left, storing the results in arrays. So, leftProduct[0] = array[0]; for j=1; j = 0; j-- rightProduct[j] = rightProduct[j+1]*array[j]; then to get our answer we just overwrite the original array with the desired product array[0] = rightProduct[1]; array[n-1] = leftProduct[n-2]; for j=1; j < n-1; j++ array[j] = leftProduct[j-1] * rightProduct[j+1] and clearly this solution is O(n) since we just traversed the data 3 times and did a constant amount of work for each cell. betterStill, I think you have the answer the interviewer wanted.. But... if the array is google sized, don't we have to worry about overflows? it looks to me can be done in order n time given the following relation: product[n] = product[n-1]*array[n-1]/array[n] for example we have array 2 3 4 5 6 product[0]=3*4*5*6 product[1]=2*4*5*6 array[0] = 2; array[1]=3 product[1]=product[0]*array[0]/array[1] Here are my 2 cents to do this in memory without creating temporary arrays. The simple solution , if division was allowed, was multiple all the elements of the array i.e. tolal = A[0]*A[1]]*....*A[n-1] now take a loop of array and update element i with A[i] = toal/A[i] Since division is not allowed we have to simulate it. If we say X*Y = Z, it means if X is added Y times it is equal to Z e.g. 2*3 = 6, which also means 2+2+2 = 6. This can be used in reverse to find how mach times X is added to get Z. Here is my C solution, which take pointer to array head A[0] and size of array as input void ArrayMult(int *A, int size) { int total= 1; for(int i=0; i< size; ++i) total *= A[i]; for(int i=0; i< size; ++i) { int temp = total; int cnt = 0; while(temp) { temp -=A[i]; cnt++; } A[i] = cnt; } } Speed in O(n) and space is O(1) narya trick is good but really useful as it might take more iterations depending on values... eg. 2,3,1000000000000000 so if you have 3 numbers and if you are trying for the first one it will go for 500000000000000 iterations, hence as the overall product value wrt to the value matters a lot... try something else.... narya, your solution is not O(n). You have to also account for how many times you will run through the inner loop - which will be a lot. You can do it in O(n) time and O(n) space. In one pass, populate B[i] with the product of every number before i. In the second pass, multiply this with the product of every number after i. Can't think of a way to do it without the second array. void ArrayMult(int *A, int size) { runningProduct = 1; int *B = new int[size]; for(int i = 0; i = 0; --i) { B[i] *= runningProduct; runningProduct *= A[i]; } for(int i = 0; i < size; ++i) { A[i] = B[i]; } } Show more responses <strong>Brutefoce Method : </strong> The brute-force method suggests that if we take each element, multiply all elements and store the product in the array B[i], then it would take O(n^2) time. <strong>Other Solution : </strong> The other solution to this problem can be we multiply all the elements of the array "A" and store the product in a variable (say product.), and then divide the product by each element, then we will get the desired array. The C code of the solution can be : #include int main() { int n,i=0; scanf("%d",&n); int arr[n]; int brr[n]; int product = 1; for(i=0;i This solution will take O(n) time. The space complexity of this solution will be O(1). If we have particularly given that "We can't use the *DIVISION* operator, then the solution to this problem will be as follows." polygenelubricants method : Let we have 2 arrays, "A" and "B". Let the length of "A" is 4. i.e. {A[0],A[1],A[2],A[3]} Then we will make two arrays (say temp1 and temp2). One array will be storing the product the array before a particular element and temp2 will store the product of elements after a particular element. temp1 = { 1 , A[0] , A[0]*A[1] , A[0]*A[1]*A[2]} temp2 = {A[1]*A[2]*A[3] , A[2]*A[3] , A[3] , 1} And then we will correspondingly multiply temp1 and temp2 and store in B. B = {A[1]*A[2]*A[3] , A[0*A[2]*A[3] , A[0]*A[1]*A[3] , A[0]*A[1]*A[2]} The C code to this solution will be : #include int main() { int n,i=0; scanf("%d",&n); int A[n],B[n]; int temp1[n], temp2[n]; for(i=0;i=0;i--) { temp2[i] = product; product *= A[i]; } for(i=0;i The time complexity to this solution will be O(n) and the space complexity to this problem will also be O(n). We can fill two arrays: headProduct and tailProduct. Each headProduct[i] == product of A[0..i-1], tailProduct[i] ==[i+1..A.lenght-1]. They can be built in O(n) and the result could be gathered in O(n). Memory demand is O(n) Not commentary nt a[N] = {1, 2, 3, 4}; int products_below[N]; int products_above[N]; int p=1; int p1=1; for (int i=0;i def solve(arr,n): product_arr=[1]*n product=1 for i in xrange(n): product_arr[i]*=product product*=arr[i] product=1 for i in xrange(n-1,-1,-1): product_arr[i]*=product product*=arr[i] return product_arr {{{ If A = {a0, a1, a2, ... an} Construct two arrays called left_p left product and right_p right product: left_p = {1, a0, a0 * a1, a0 * a1 * a2, .... , a0 * a1 * a2 ... * an-1} right_p = {a1*a2*...*an, ....... an-2 * an-1 * an , an-1 * an, an , 1} prod_p[i] = left_p[i] * right_p[i]; }}} O(N) Solution!!! static void Calculate(int[] iArr) { int total = 1; for (int i = 0; i < iArr.Length; i++) { total *= iArr[i]; } for (int i = 0; i < iArr.Length; i++) { iArr[i] = (int)(total * (1 / (double)iArr[i])); } } The answer I post above this uses division. Oops. Here is an answer without division static void Calculate(int[] iArr) { int total = 1; for (int i = 0; i 0) { temp -= iArr[i]; newVal++; } iArr[i] = newVal; } } Sorry, that last one didn't paste properly static void Calculate(int[] iArr) { int total = 1; for (int i = 0; i 0) { temp -= iArr[i]; newVal++; } iArr[i] = newVal; } } Show more responses p = 1 g = 1 for x in nums: g = g* x + p p = p + x return g Way easy with a simple negative exponent var arr = [2,3,4,5] var prod = arr.reduce((a,b,arr)=>a*b) arr.map((x)=>Math.pow(x,-1)*prod) console.log(arr) //[60,40,30,24] I don't know if this is correct. But i think it is. I have done it with python def multiply(numbers,n): total = 1 for x in numbers: if x != n: total *= x return total a = [10, 3, 5, 6, 2] n = 4 prod = [] for i in a: re = multiply(a,i) prod.append(re) - create a binary tree with the values of array as leaf node - each parent is the product of its children - once the tree is formed, for each value/leaf traverse the tree to the top, each time multiplying the sibling -if tree construction time is ignored, this will take logn time for each calculation and nlogn time for all elements int[] array = new int[]{2,3,4,5}; int m = 1; int m2 = 1; int[] array1 = new int[array.length]; int[] array2 = new int[array.length]; for (int i = 0, j = array.length - 1; i < array.length; i++, j--) { m *= array[i]; array1[i] = m; m2 *= array[j]; array2[j] = m2; } for (int i = 0; i < array.length; i++) { if (i == 0) { System.out.println(array[i] + " " + m2 / array[i] + " " + array2[i + 1]); } else if (i == array.length - 1) { System.out.println(array[i] + " " + m2 / array[i] + " " + array1[i - 1]); } else { System.out.println(array[i] + " " + m2 / array[i] + " " + array1[i - 1] * array2[i + 1]); } } Of course, if allow more temp arrays it can be done in one iteration int[] array = new int[]{2, 3, 4, 6}; int m = 1; int m2 = 1; int[] array1 = new int[array.length]; int[] array2 = new int[array.length]; int[] array3 = new int[array.length]; int middle = array.length / 2; for (int i = 0, j = array.length - 1; i = middle) { if (i + 1 != array.length) { array3[i] = array1[i - 1] * array2[i + 1]; } else { array3[i] = array1[i - 1]; } if (j - 1 >= 0) { array3[j] = array1[j - 1] * array2[j + 1]; } else { array3[j] = array2[j + 1]; } } } for (int i = 0; i < array.length; i++) { System.out.println(array3[i] + "===" + m2 / array[i]); } Need help in writing Scala Program for multiplication of 2 elements of array and last element should not exceed 1000. Input Array:(1,3) Output: Array(1,3,3,9,27,243...) #include using namespace std; int main() { int y=1,a[23],i,k,s,t,b[76]; cout >s; for(i=0;i>a[i]; for(i=0;i #include using namespace std; int main() { int y=1,a[23],i,k,s,t,b[76]; cout >s; for(i=0;i>a[i]; for(i=0;i let arr = [1,2,3,4,5] arr = arr.map((el,i)=>{ return arr.slice(0,i).concat(arr.slice(i+1)).reduce((a,b)=>a*b) }) console.log(arr) Show more responses traverse once and store all the product of element . For(0 to n-1) A[i]= products*pow(a[i],-1); One or more comments have been removed. |
Coderpad: given an array scores[][] = {“jerry”,”65”},{“bob”,”91”}, {“jerry”,”23”}, {“Eric”,”83”}} Find the student with highest average score 20 Answerspublic static String s[][] = {{"jerry","65"}, {"bob","91"}, {"jerry","23"}, {"Eric","83"}}; public static void main (String args[]) { int highestScore = 0; int studentIndex = 0; int temp = 0; for(int i = 0; i highestScore){ highestScore = temp; studentIndex = i; } } System.out.println(s[studentIndex][0]); Add all elements to the Hashmap , if key matches append the score to the list, now iterate through keys and keep track of avg and key, return max avg and key in the end O(N) public class BestGrade { public static void main(String[] args) { String student[][] = {{"jerry","65"}, {"bob","1"}, {"jerry","23"},{"jerry","23"}, {"jerry","100"},{"Eric","83"}}; //Map counter = new HashMap(); List score = new ArrayList(); Map> map = new HashMap(); for(int i = 0;i(); score.add(Integer.parseInt(student[i][1])); map.put(student[i][0], score); } } List grade = new ArrayList(); for(String key:map.keySet()) { score = map.get(key); int sum = 0; for(int num : score) { sum+=num; } int average = sum/score.size(); grade.add(average); } Collections.sort(grade); System.out.println(grade.get(grade.size()-1)); } } Show more responses import java.util.*; import java.util.stream.Collectors; class Student{ private String name; private Float averageMark = 0.0f; private int numberOfSubjects = 0; public Student(String name){ this.name = name; } public void addMark(Float mark ){ averageMark += mark; numberOfSubjects += 1; averageMark = averageMark/numberOfSubjects; } public Float getAverageMark(){ return averageMark; } public String getName(){ return name; } public Student(Float mark, String n){ name = n; averageMark = mark; } } public class MaxScore { public static String s[][] = {{"jerry","65"}, {"bob","91"}, {"jerry","23"}, {"Eric","83"},{"Eric","99"}}; public static void main(String args[]){ Map studentMap = new HashMap(); for(int i=0; i studentList = studentMap.values().stream().collect(Collectors.toList()); Collections.sort(studentList, Comparator.comparing(Student::getAverageMark).reversed()); System.out.println(studentList.get(0).getName()); } } you can have a hashmap with key string and arraylist of size2 where u can store the current sum in 0 index and num of scores in 1 index public static void main(String[] args) { String student[][] = {{"jerry","65"}, {"bob","1"}, {"jerry","23"},{"jerry","23"}, {"jerry","100"},{"Eric","83"}}; Map student> = new HashMap(); float max_avg=0.0; String key; for(int i = 0;i(); Integer score = Integer.parseInt(student[i][1])); if(map.containsKey(student[i][0]) { Integer sum = map.get(student[i][0]).get(0); Integer num = map.get(student[i][0]).get(1)+1; sum=sum+score; map.get(student[i][0]).set(0,sum); map.get(student[i][0]).set(1,num); avg =sum/score; if(avg>max_avg) { max_avg=avg; key=student[i][0]; } else { List ar = new ArrayList(); ar.add(score); ar.add(1); map.put(student[i][0], ar); } } System.out.println(map.get(key)); } O(n) solution single pass public static Integer bestAverageGrade(String[][] scores) { List s = new ArrayList(); List grade = new ArrayList(); Map> map = new HashMap>(); for(int i = 0;i public static Integer bestAverageGrade(String[][] scores) { List s = new ArrayList(); List grade = new ArrayList(); Map> map = new HashMap>(); for(int i = 0;i package Hello; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import static java.util.Comparator.comparingInt; public class hello { public static class Average { public int count; public int num; public int average; public Average(int count, int num, int average) { super(); this.count = count; this.num = num; this.average = average; } public Average() { super(); } } public static void main(String[] args) { String s[][] = {{"jerry","65"}, {"bob","91"}, {"jerry","23"}, {"Eric","83"}, {"bob","10"}}; Map map = new HashMap(); int avera = 0; try { for(String x[]:s) { if(map.containsKey(x[0])) { Average avg = map.get(x[0]); int val = avg.num + Integer.parseInt(x[1]); int count = ++avg.count; int average = val/count; map.put(x[0], new Average(count, val , average)); } else { if(x[0] != null) { int val = Integer.parseInt(x[1]); map.put(x[0], new Average(1, val, val )); } } } avera = map.entrySet() .stream() .max(comparingInt(e -> e.getValue().average)).get().getValue().average; } catch(Exception e) { } System.out.println(avera); } } Can anybody please tell, If anything is wrong with this simple approach : public class StudentWithMax { private static class Student { public String name; public Double avg; Student(String n, Double a) { name = n; avg = a; } } public static void main(String[] args) { String[][] s = { { "Jerry", "65" }, { "Bob", "92" }, { "Jerry", "33" }, { "Eric", "83" }, }; Student maxStudent= new Student("", (double)Integer.MIN_VALUE); for (String[] strings : s) { //System.out.println(strings[0]); if(Double.parseDouble(strings[1]) > maxStudent.avg) { maxStudent.name=strings[0]; maxStudent.avg=Double.parseDouble(strings[1]); } } System.out.println("name: "+maxStudent.name + ", avg: " + maxStudent.avg); } } Solving same problem using Java 8: import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class MaxScore { public static String s[][] = {{"jerry","65"}, {"bob","91"}, {"jerry","23"}, {"Eric","83"}}; public static void main(String[] args) { List arrayOfLists = Arrays.asList(s); List students = arrayOfLists.stream().map(s->new Student(s)).collect(Collectors.toList()); Optional studentWithMaxScore = students.stream().max(Comparator.comparing(Student::getScore)); System.out.println(studentWithMaxScore.get().getScore()); } } class Student{ private final String name; private final int score; public Student(String[] s) { String name = s[0]; String score = s[1]; this.name = name; if(score.matches("-?\\d+(\\.\\d+)?")) { this.score = Integer.parseInt(score); } else { this.score = 0; } } public String getName() { return name; } public int getScore() { return score; } } package com.rsb.hack; import java.util.ArrayList; import java.util.List; public class Maxsumarray2D { public static void main(String[] args) { String[][] str = { { "Bob", "80" }, { "Rob", "70" }, { "Charles", "85" }, { "Bob", "100" }, { "Charles", "75" } }; int sum = 0; List ls = new ArrayList(); for (int row = 0; row < str.length; row++) { for (int col = 0; col < str[row].length; col++) { if(col!=0) { sum+= Integer.parseInt(str[row][col]); } } } System.out.println(sum); Double avrage=(double) (sum/str[0].length); System.out.println(avrage); } } public static void avrage() { String[][] str = { { "Bob", "80" }, { "Rob", "100" }, { "Charles", "50" }, { "Bob", "80" }, { "Charles", "50" } }; int sum = 0; Map map = new HashMap(); for (int row = 0; row < str.length; row++) { for (int col = 0; col < str[row].length; col++) { if (col == 0) { name=str[row][col]; } if (col != 0) { b= Integer.parseInt(str[row][col]); } if(map.containsKey(name)) { int sum1=map.get(name); int total=sum1+b/2; map.put(name, total); total=0; b=0; } else { map.put(name, b); } } } System.out.println("map value-------"+map); } Show more responses package com.rsb.hack; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class Maxsumarray2D { static String name = ""; static int b = 0; public static void main(String[] args) { avrage(); } public static void avrage() { String[][] str = { { "Bob", "80" }, { "Rob", "100" }, { "Charles", "50" }, { "Bob", "80" }, { "Charles", "50" } }; int sum = 0; Map map = new HashMap(); for (int row = 0; row la:map.entrySet()) { if(la.getValue()>avgmax) { avgmax=la.getValue(); } } System.out.println("avgmax----"+avgmax); } } import java.util.HashMap; import java.util.Map; public class BestAverageGrade { public static void main(String[] args) { // TODO Auto-generated method stub String s[][] = {{"jerry","65"}, {"bob","91"}, {"jerry","23"}, {"Eric","83"}}; HashMap hm = new HashMap(); for(int i=0;i entry : hm.entrySet()) { System.out.println(entry.getKey()+" " + entry.getValue()); } double average = Double.MIN_VALUE; String name=""; for(Map.Entry entry : hm.entrySet()) { if(entry.getValue() > average) { name = entry.getKey(); average = entry.getValue(); } } System.out.println(name+" "+average); } } We can use java-8 streams API to get the student with maximum marks easily in 2 line of codes. String [][]scores = {{"jerry","65"},{"bob","91"}, {"jerry","23"}, {"Eric","83"}} ; Map collect = Arrays.stream(scores).collect(Collectors.groupingBy(a -> a[0], Collectors.averagingInt(a->Integer.parseInt(a[1])))); Entry studentWithMaxMarks = collect.entrySet().stream().max((e1,e2) -> Double.compare(e1.getValue(), e2.getValue())).get(); System.out.println( studentWithMaxMarks.getKey() +" : "+studentWithMaxMarks.getValue() ); package com.company; import java.util.*; public class BestGrade { public static void main(String[] args) { String student[][] = {{"jerry","65"}, {"bob","60"}, {"jerry","42"},{"jerry","65"}, {"jerry","100"},{"Eric","63"}}; Map> map = new HashMap(); for(int i = 0; i templst = new ArrayList(student.length); if (map.containsKey(student[i][0])) { templst.clear(); templst = map.get(student[i][0]); templst.add(Integer.parseInt(student[i][1])); } else { templst.clear(); templst.add(Integer.parseInt(student[i][1])); } map.put(student[i][0],templst); } String highestAverageStudent = ""; double highestAverage = 0; for(String key : map.keySet()) { double average = map.get(key).stream().mapToInt(val -> val).average().orElse(0.0); if (highestAverage < average) { highestAverage = average; highestAverageStudent = key; } } System.out.println(highestAverageStudent); } } public class HighestMarks { //Coderpad: given an array scores [][] = {“jerry”,”65”},{“bob”,”91”}, {“jerry”,”23”}, {“Eric”,”83”}} //Find the student with highest average score public static String s[][] = {{"jerry","65"}, {"bob","91"}, {"jerry","23"}, {"Eric","83"}}; public static void main (String args[]) { int highestScore = 0; int studentIndex = 0; int temp = 0; // s.length should returns no of row for(int row = 0; row highestScore) { highestScore = marks; studentIndex = row; } } System.out.print("Student with highest marks:"+s[studentIndex][0]); } } /** Input: [{"Bob","87"}, {"Mike", "35"},{"Bob", "52"}, {"Jason","35"}, {"Mike", "55"}, {"Jessica", "99"}] Input [["Bob","87"], ["Mike", "35"], ["Bob", "52"], ["Jason","35"], ["Mike", "55"], ["Jessica", "99"]] Output: 99 Explanation: Since Jessica's average is greater than Bob's, Mike's and Jason's average. */ const calculateAvgGrade = (arr) => { if(arr.length == 0) { return; } // O(K) Space Complex where K is number of unique Keys const hashMap = new Map(); let highest = -Infinity; // O(N) Time Complexity - where N is arr length arr.forEach((element) => { if(!hashMap.has(element[0])) { hashMap.set(element[0], {count: 0, totalScore: 0 }); } let temp = hashMap.get(element[0]); temp.count++; temp.totalScore = temp.totalScore + Number(element[1]); hashMap.set(element[0], temp); }); hashMap.forEach((value, key) => { let temp = Math.floor(value.totalScore/value.count); if(temp > highest) { highest = temp; } }); return highest; }; li = [["jerry",65],["bob",91], ["jerry",23], ["Eric",83]] def get_student_with_highest_avg(li): stu_dict = {} for stu in li: stu_name = stu[0] stu_marks = stu[1] if(stu_name in stu_dict): stu_prev_avg = stu_dict[stu_name] stu_avg = (stu_marks + stu_prev_avg)/2 stu_dict[stu_name] = stu_avg else: stu_dict[stu_name] = stu_marks max_avg = 0 student_name_with_highest_avg = '' for item in stu_dict.iteritems(): if(item[1] > max_avg): max_avg = item[1] student_name_with_highest_avg = item[0] return student_name_with_highest_avg, max_avg print(get_student_with_highest_avg(li)) One or more comments have been removed. |
Consider an X x Y array of 1's and 0s. The X axis represents "influences" meaning that X influences Y. So, for example, if $array[3,7] is 1 that means that 3 influences 7. An "influencer" is someone who influences every other person, but is not influenced by any other member. Given such an array, write a function to determine whether or not an "influencer" exists in the array. 12 AnswersThis was a tough one that forces you to consider how best to traverse the array and eliminate possibilities as soon as possible. Not_Influencers[n] = 0; //Make all elements 0 for (i = 0 ; i< n ; i++){ if(Not_Influencers[i] == 1) continue; row_sum = find_row_sum(a[i]); if(row_sum == n-1 && find_col_sum(i) == 0) return Found; for(j = i; j < i; j++) if (a[j] == 1) Not_Influencers[j] = 1; } X should be equal to Y, right? Show more responses //if vec[i][j] == 0 then i is not an influence //if vec[i][j] == 1 then j is not an influence //so time complexity is O(n) bool find_influences(vector > &vec) { int n = vec.size(); vector not_influence(n); for (int i = 0; i = 0; --j) { if (!vec[i][j]) { break; } not_influence[j] = 1; } if (j < 0) { return true; } } not_influence[i] = 1; } return false; } Run a BFS or DFS. For each node keep going to influencer. Find a node which can be reach by all nodes. Sort of finding sink node. public static int influencer(final int[][] jobs, final int r, final int c) { int[] degree_in = new int[jobs.length]; int[] degree_out = new int[jobs.length]; for (int i = 0; i < r; ++i) { for (int j = 0; j < c; ++j) { if(jobs[i][j] == 1) { // i influences j degree_out[i]++; degree_in[j]++; } } } for (int i = 0; i < r; ++i) { if (degree_out[i] == r - 1 && degree_in[i] == 0) { return i; } } return -1; } Consider the input as Graph given in adjaceny matrix representation. Find whether a semi-eulerian path is present in the graph or not. Take the XOR product of the original matrix with the transposed matrix and sum by row. If any row counts equal the rank then they are influencers. private static boolean hasInfluencer(int[][] matrix) { if (matrix == null) return false; if (matrix.length == 0) return false; boolean result = false; for (int i=0; i the XOR suggestion I think is incomplete. The condition sum(row_influencer) = 1 and sum(column_influencer) = N so a simple matrix multiplication with the transposed should give for the vector v[influencer] = N and v[N-influencer] = 1. I assume influencer influences himself. def find_influencer(matrix): for row in range(len(matrix)): following_none = not any(matrix[row]) if not following_none: continue all_following = True for r_no in range(len(matrix)): if not row == r_no: continue if not matrix[r_no][row]: all_following = False break if all_following: return row return -1 Here is a different view. Please comment if you find any issues with the logic. 1st. condition: An influencer can not be influenced by any one. Let's say the in a matrix of [x.y], there is an influencer with index 2. So, the column=2 (3rd column) in the matrix must be all 0s, since the influencer can not be influenced. Step 1: Find a column with all 0s. If found, remember the column index or there is no influencer. Let's say, it is m Second condition: An influencer must have influenced everyone. So, in our example: row=2 (third row) must be all 1s except for column=2, since influencer can not even influence self. Step 2: Check row=m and find that all values are 1 except for [m][m]. If found, we have an influencer. |
Write a probability formula to tell how many bits will be changed when 1 is added to a 32 bit binary number. 11 AnswersThe probability of N bits being changed is (1/2)^N. The reason: the number of bits that will change depends on the position of the first zero that appears in the number. If the first zero is at the LSB, only one bit changes; if it is in the third position, the three bits upto the first zero change. Now, it boils down to the probability of finding the first zero. Assuming that the zeros and ones appear with equal probability in a given number, the probability of finding the first 0 in the Nth position is (1/2)^N. For more, look up the Geometric Random Variable. I think that you need to take into account that if you want to toggle 2 bits, you can only do if you flip bits from position 0..30. Toggling bit 31 is only going to toggle this bit no matter what. Therefore, you need to multiply (33-N)/32 to your proposed result, to keep this into account. @Mythreya's analysis is correct but incomplete. To get the expected value, you have to multiply the number of bits by their probability. Answer is Sigma{k/(2^k)} for k = 1 to 32. Show more responses Using this approach, the answer is 2 bits will change on an average: https://answers.yahoo.com/question/index?qid=20110413165236AAU9tmO @Henry David Thoreau: The question is not asking for expected value, just the discrete density function. Also P(k=32) needs special handling. @Henry, no ... probability that at least 1 bit will change is (k/2^k); but, probability for all k bits to change, I guess, would still be 1/2^k. Right? And, k=0 to 31 !! k=1-32 p=k/2^(k-1) E(n) = 1 + E(n-1) / 2 where E(n) is the expected number of bit changes when 1 is added to an n-bit integer. E(1) = 1. E(2) = 1 + E(1) / 2 = 1.5. E(3) = 1 + E(2) / 2 = 1.75 We can verify it for n = 3. The possible values are as follows 000 -> 1 change 001 -> 2 change 010 -> 1 change 011-> 3 change 100-> 1 change 101-> 2 change 110-> 1 change 111-> 3 change Total changes: 14 Expected change = 14 / 8 = 1.75; answer is (2^1+2^2+2^3....2^32)/(32*(2^32)) If we just look at two bits - (b1,b2) f(b1) = { 1 b1=0; f(b2) if b1=1}, the probability of one bit changing is half. The probability of two bits changing is half * f(b2), which is half*half if b2=0 and half*half*f(b3) if b2=1. Therefore, for k=1-31 p(k) = 1/2^k and for p(k=32) = 1/2^k because when the 32nd bit flips there is nothing more to be done and the recursion stops |
Write some pseudo code to raise a number to a power. 11 Answerspretty trivial... int raise(num, power){ if(power==0) return 1; if(power==1) return num; return(raise(num, power-1)*num); } double Power(int x, int y) { double ret = 1; double power = x; while (y > 0) { if (y & 1) { ret *= power; } power *= power; y >>= 1; } return ret; } Show more responses In Ruby: def power(base, power) product = 1 power.times do product *= base end product end puts "2^10 = 1024 = #{power(2,10)}" puts "2^0 = 1 = #{power(2,0)}" puts "2^1 = 2 = #{power(2,1)}" If I were an interviewer, I would ask the Aug 29, 2010 poster why he used bitwise operators, and whether he would deploy that code in a production environment, or if he merely wanted to demonstrate, for purposes of the interview, that he understands bitwise operations. Because it uses dynamic programming and is lots more efficient than your algorithm. If the power is not integer, use ln and Taylor series If I'm the interviewer, none of above answers is acceptable. What if y < 0? what if y < 0 and x == 0? I'm seeing an endless recursion that will eventually overflow the stack, and the none-recursive one just simply returns 1. There is a way to do this in a logN way rather than N. function power(x, n) { if n == 1 return x; // Even numbers else if (n%2 == 0) return square( power (x, n/2)); // Odd numbers else return power(x, n-1); } This is from Programming pearls.. interesting way. small mistake function power(x, n) { if n == 1 return x; // Even numbers else if (n%2 == 0) return square( power (x, n/2)); // Odd numbers else return power(x, n-1) * x; } # Solution for x ^ n with negative values of n as well. def square(x): return x * x def power(x, n): if x in (0, 1): return x if n == 0: return 1 if n < 0: x = 1.0 / x n = abs(n) # Even number if n % 2 == 0: return square(power(x, n/2)) # Odd number else: return x * power(x, n - 1) print ("0 ^ 0 = " + str(power(0, 0))) print ("0 ^ 1 = " + str(power(0, 1))) print ("10 ^ 0 = " + str(power(10, 0))) print ("2 ^ 2 = " + str(power(2, 2))) print ("2 ^ 3 = " + str(power(2, 3))) print ("3 ^ 3 = " + str(power(3, 3))) print ("2 ^ 8 = " + str(power(2, 8))) print ("2 ^ -1 = " + str(power(2, -1))) print ("2 ^ -2 = " + str(power(2, -2))) print ("2 ^ -8 = " + str(power(2, -8))) |
Senior Software Engineer at Google was asked...
Create a stack of numbers where the maximum number is always known. 10 AnswersCreate a separate stack for the maximums. maintain a sorted stack, the insert would look like insert(int p,stack s){ stack large; int top = s.peek(); while(top>s){ large.push(s.pop()); top = s.peek(); } s.push(p); while(!large.empty()){ s.push(large.pop()); } } sorry, typo while(top>p) Show more responses I was asked of this question as well. I not sure how to implment a second stack in a way that the max number is always on top. I was asked of this question as well. I not sure how to implment a second stack in a way that the max number is always on top. To Job Seeker: The basic idea is that when a new number is being pushed onto the stack, you need to see if that number is greater than or equal to the current top of the maximums-stack. If it is, you push the number onto maximums-stack as well. Also, when pop is called, you look to see if the number being popped is equal to the number on the top of the maximums-stack. If it it, pop that stack as well. just saw this, i think u can just map your number into an object, that has both the maximum number, and the last number that you've pushed in just peek the stack before you push, compare the peek'd value 'vs' your new pushed number, then replace or update the max number as you see fit? if you're only allowed to push numbers into your stack, just push your number in the stack more than once (at-least three times) indicating that every value that you put in is a sequence of 2 numbers, and so, push another one (the 3rd, which will always be your maximum number) so on every 3 pushes, you've stored the maximum value, then everytime you push something in, just peek the last 3 values in the stack, knowing that the 2nd and 3rd value was probably the number you pushed in, and the first 1 was the max value it's funny Sort the array so that the numbers are in descending order this way you know for sure the first element is the maximum number. Maintain your Stack ADT like this: class Node { T data; T max; Node next; } class Stack { Node top; push(T value) { } } Maintain your Stack ADT like this: class Node { T data; T max; Node next; } class Stack { Node top; void push(T value) { Node node = new Node(); node.value = value; if(top == null) { node.max = value; } else { node.max = value.compareTo(top.max) > 1 ? value : top.max; } node.next = top; top = node; } T pop() { if(top == null) { return null; } T val = top.val; top = top.next; return val; } T max() { return top == null ? null : top.max; } } public static void main(String[] args) { Stack stack = new Stack(); stack.push(3); stack.push(2); stack.push(5); System.out.println(stack.max()); // 5 System.out.println(stack.pop()); // 5 System.out.println(stack.max()); // 3 System.out.println(stack.pop()); // 2 System.out.println(stack.max()); // 3 System.out.println(stack.pop()); // 3 } |
Senior Software Engineer at Apple was asked...
In a stream of integers from 1 to n, only one number will be repeated. How can you tell what that number is? 11 AnswersThis felt like a brain teaser question to me, and since I hadn't heard it before it took me a little while to come up with a solution that involved using a factorial function. You know n. S = n*(n+1)/2 is the sum of 1st n numbers. P = sum of the n+1 numbers you are provided with. Finding P given an array of n+1 integers can be done in O(n). P - S is the repeated integer. Heres an explanation, http://www.techinterview.org/post/526329049/sum-it-up Show more responses int sum = 0; int xorSum = 0; for(int i =0 ; i < n; i++) { sum += input[i]; xorSum ^= input[i] } return (sum - xorSum)/2; Mat, try 1,2,2,3: 1+2+2+3= 8 1^2^2^3= 2 (8-2)/2=3?2 A hash table would resolve the question with O(n) Add to HashSet. It will return true if it exists. If you're writing it in ruby def find_repeat(numbers) numbers.length.times{|n| return numbers[n] if numbers[n] != n } end lmao, ok everyone getting a little craycray, why not just simply this.... int prev << stream; while (stream) { int curr << stream; if curr == prev return else prev = curr; } (sum_of_numbers - (n*(n-1)/2)) Add each integer to the map if it doesn’t already exist as key if it’s exists then it is a repeated number. |
Traverse nodes in a binary tree 11 AnswersWhat is taught in compsci, and even what's in Knuth, isn't entirely right on modern out-of-order execution core CPUs void traverse(Node node){ if(node == null) return null; System.out.println(node.data); traverse(node.left); traverse(node.right); } It can't be that this candidate really serves on a language committee. I find it difficult to believe that someone who serves on a language standards committee doesn't care about the difference between an O(N^2) and an O(logN) solution, for that would be horrifying indeed. And in defense of the employee conducting the interview, if I did see a candidate that didn't care about the difference between the two, I really wouldn't care what they have on their resume. They could be a Turing award winner for all I would care. There's a valid point about spatial locality, etc, but for something like N = 10^6 (for example), I'll take even O(logN) disk reads (*gasp*), over N^2 quick register operations any day.. Show more responses Well, I do serve on language committees, two to be precise (though one is mostly in a feed forward role). And I do care about the difference between O(N^2) and O(log N)! I gave a complex answer to the interviewer because there is so much "it depends on the situation and circumstance". Other companies had interview processes which coped far better with the ambiguity, but from what I saw Amazon's are very "by the book" black and white. Look, I interviewed for four roles within Amazon and all four interview experiences ranged between bad and truly awful, which is why I chose neither the worst nor best experience and wrote up a review of it here as representative of *my* personal experience. Some of my experiences with other Fortune 500 companies were equally awful, and there are reviews for those on here too. However, I did also have many very good interview experiences, and I begin work with one Fortune 500 company in the Fall with whom my interview experience - over 20+ hours over twelve interviewers - couldn't have been better. Tip to interviewers: it *really* helps if you at least read the abstracts of the academic papers the interviewee has written. You could easily segment those companies which do this from those which don't, and Amazon from my four experiences with them don't or didn't. I hope you weren't offended too much by my earlier comment. Your explanation just now puts things into better context. I have to admit that upon initially reading your original review it wasn't very clear to me that you understood or cared about the difference between O(logN) and O(N^4). If the company was also unclear on that, you have to admit that one can see why they wouldn't extend an offer. Of course not everything is about big-O, but you should still be able to give answers in terms of it when needed. It's great if you know about data locality and caches, but you should still be able to show the basic analysis too. On another point, of course you should try to reuse code, but you also need to demonstrate (in an interview more than ever) that you have the skills to write new code when necessary, not by pointing them to some open source project you did, but by writing some nice, clean code for them right on the spot. A demonstration of your high skill level is more impressive than a description. It's a proof-by-demonstration sort of culture. You might ask why anyone should re-invent the wheel, but I'll leave you with this: if you can't prove to them that you *can* reinvent the wheel, why would they believe you have the creativity needed to invent a motorcycle? Wasn't offended at all - in fact, your comment is by far the best made on this thread (as you can tell from everything else being deleted by glassdoor). And besides, caustic opinions of your opinions are part of publishing an opinion, I'm well used to it. My issue with Amazon - and it's one shared by my buddies within Amazon too - is there is too much box ticking of standardized procedures in the recruitment process. That rewards rote pre-learning the answers to the live programming tasks you do over the telephone (search google, you'll find precompiled cheat sheets for Amazon and indeed many of the big tech companies). That's hardly "writing some nice, clean code for them right on the spot" as you suggest. A github repo with 40,000 lines of code stretching over a decade is much harder to fake. Amazon ought to hire on that in preference, but their recruitment process requires a standardized approach. The company I start with in the Fall used a completely unstructured process. They interview you on things that THEY don't know anything about let alone you, and topics which have absolutely nothing to do with compsci or technology, so for example one topic was on mining copper on the Mongolian steppes. I know very little about that, and neither did they. But as the elite of the elite team (within the company) said at the start of the interview, "we're not going to talk at all about anything to do with code during this interview. We'll know if you're a good hire by seeing how you think on topics both you and us know nothing about". That company offered the lowest compensation of any offers I received. But boy, what a great interview experience, so I had to accept. I hope working there is even 10% as good as they came across during the interviews. If so, I'm more than happy with lower pay. I'm no 10x programmer, maybe a 4x, so I'm not the perfect recruit. But I don't think Amazon should have failed me on stage 1 of each of the four roles I interviewed for. Hence the review. Mining copper on the Mongolian steppes, huh? That must be a very unique company. They're actually a multinational quite similar to Amazon - well known to consumers, occasionally known for moments of brilliance, otherwise fairly dull and dependable. Mining copper was one of many curve ball interview topics. Off the top of my head other topics included the technology policies of Kim Jung Il in North Korea, something about water and Tar Sands in Canada which I forget now, whether and how Russians are naturally good at science and math, how would you go about reconciling quantum physics with relativity, conflict resolution strategies between culturally disjunctive teams - and the list goes on much further (all this was many months ago now, so I'm forgetting). All this for a standard software engineering role, so I'm expected to be in a cubicle coding, not organizing world peace. Looking back on it now, it should have freaked me out much more than it did at the time. I suppose I was interviewing with so many companies at the same time it all just blurred. Anyway, we're getting off topic from Amazon's interview strategies. Amazon *are* a great company. They've soaked up the best and brightest from Microsoft particularly and it's a much less dysfunctional working environment than Microsoft where something went wrong a long time ago, but no one can agree exactly what, and even if they could agree, top management don't seriously think it's a problem. However Amazon is naturally silo-ized, where the consumer goods division is quite different to consumer services which is quite different to cloud provision and even cloud reliability provision. The problem, I think, is that Amazon's HR would prefer every engineer to be hired according to similar criteria, and that's where this box ticking standardized list of coding exercises comes from. As a comparison, Google's silo structure and hiring process is not dissimilar, though Google do run an elite expedited recruitment pathway which skips all the normal hoop jumping nonsense at the cost of fast tracking only those with the very best academic grades from the best US universities, or are famous. I have pretty terrible grades with a lot of bare scraping passes, none from Ivy League anything, and I'm not Dennis Richie or Rob Pike or Guido van Rossum famous. Still, it's interesting how companies start to struggle so hard with high skilled recruitment as they get bigger. It's not like there aren't very good HR books on the topic, yet no one in the HRs of these big famous tech multinationals seems to ever read them (or if they do, they sure don't implement them). I guess what I'm saying is that tech recruitment is hard, but it's not NP hard. Just be organized and constantly reflect on your hiring system. A very good start for Amazon would be to read these reviews on Glassdoor, and proactively enact changes so they're not failing candidates like me at stage 1 in the interview process (fail me later for lack of fit sure, but not on the initial programming exercise when I have 40k lines of open source contributions and I serve on ISO - that sort of indicates I'm not an incompetent programmer). Amazon also ought to knock some humility into some of their engineers, as a minority of them were rude and ignorant (I had one storm out during the telephone interview after giving a torrent of invective about me personally after I showed him up on a series of technical mistakes, and his colleague was clearly very embarrassed. As I said to him, "really, honestly don't worry about it, I've heard far worse said about me. But you can forget me ever working for Amazon after that"). I haven't posted a review of that interview on glassdoor because it was probably not representative of Amazon in general and the guy in question was probably just having a really bad day, though as I mentioned earlier, all four of my interviews did not go well. I just hope my review here has some effect within Amazon one day. As I said earlier, it *is* a great company. I agree with you. You have to focus on the person's ability to find answers not re-invent the wheel. If I were interviewing someone...as long as he can google a problem take me to an answer which perfectly fits the needs and then explain the solution (instead of blindly copying/pasting it) to me clearly, that would be the perfect candidate for the job. These kind of questions are only suitable for fresh out of college grads not people who have been in the industry for a long time. @NikB: Thanks for the comment. Certainly when I've been interviewing others, I'm generally fairly shocked at how awful the average candidate is - I mean, I catch an easy third who have lied on their resume and that's with five minutes of googling (depending on the lie, if they admit it in the interview, I actually give them a pass on it because I know what it's like to have poor grades from no name universities). About two thirds clearly have no integrity and will tell you whatever they think you want to hear, and I personally can't have that on my own teams (I won't veto hires for other teams on this though). About three quarters have no evidence that they seriously self-engage in continuing professional development e.g. teaching themselves new skills not directly needed for work. I would *far* prefer a poor programmer who continually self improves over a rock star programmer. I would *far* prefer a programmer who uploads even crappy non-reusable bits of personal script to github than someone who claims they have always been too busy to get round to it. It gives me extra information to evaluate that candidate. Less information = more uncertainty = much higher chance of me choosing elsewhere. A true coder codes all the time including people and social structures, and I want those on my team irrespective of skill. I agree only about half of those are willing to share their work with others, so lack of sharing does exclude a lot of worthwhile hires. But I guess we all have our personal preferences on what we think works best. Some colleagues of mine who I respect greatly think my hiring philosophy bananas! Do you mind if I ask what those 3 algorithms that you wrote are? |
Senior Software Engineer at Google was asked...
Intersection of two numerical arrays 8 AnswersAlgorithm and pseudo code * assuming b[] is the longer array quick sort b[] for all items from a[] binary search this item in b[] for above.. O(n log n) + O(n) * O(log n) Show more responses I have a O(n) algorithm: 1. Iterate over all the elements of first array a[] and build a dictionary mapping the element value to the index - O(n) 2. Now iterate over all the elements of the second array b[] and for each element that is already present in the dictionary, move the element to a different array that maintains the intersection elements - O(n) 3. Hence the overall complexity is O(n) in time and O(n) for the dictionary and the array to maintain the intersection elements. given arrays of lengths n and m. A simple solution is to sort array n in O(n lg n) and for each item in array m, look for it in sorted n, O(m lg n). So total time = O((m+n)lg n), let array n be the short array. I feel there is a much quicker solution, maybe O(n+m) if we assume integers. Two possible approaches: 1. Sort both arrays and then walk over each array simultaneously until you find all the common entries. This is O(n*logn) to do the sort and then walking over the items is O(n). 2. Walk over first array and insert each item into a hash table. Then search for each item in the hash table. This is O(n) time and O(n) space. If you're doing this a lot with the same sets of data, both algorithms allow you to do the expensive step once for each array and then find the common items in linear time. Simple O(n) solution: public static Integer[] getIntersection(Integer[] a, Integer[] b) { Map countsMap = new HashMap(); for(Integer num : a) { // O(n) time countsMap.merge(num, 1, (x, y) -> y + 1); } List intersection = new LinkedList(); for(Integer num : b) { // O(n) time if(countsMap.containsKey(num)) { // O(1) int count = countsMap.get(num); // O(1) if(count > 0) { intersection.add(num); // O(1) countsMap.put(num, count - 1); // O(1) } } } // Above loops run in O(n) time each. // Total time complexity = O(2n) return intersection.toArray(new Integer[intersection.size()]); } Actually, even conversion of list to array happens in O(n) time. So above solution required O(3n) and not O(2n), Please pardon my mistake. |
Behavioral Why outreach The impact you hope to have from your next role?What is most important factor in your career/job What do you think about RSpec? How do you compare it with other frameworks What was the hardest/Challenging technical problem you faced and how did you resolve it Coding This problem concerns finding a time when we can do daily recurring maintenance on a server. You are to write a function that is given the following information: List of times when the server is busy every day Duration, in minutes, of the desired maintenance window The function should return the start time of a daily maintenance window when the server is not busy. In pseudo-code, the function signature would look something like this: maintWindowStart(busyTimes, durationMins) -> startTime The "busy times" should be time ranges like the following, and can be represented in whatever data structure you feel is appropriate. 0:05 to 0:30 = [5, 30] 2:00 to 4:01 = [120, 241] 13:10 to 16:55 = [790, 1015] [[5, 30], [120, 541], [790, 1015]] // requested duration -> expected start time // 10 -> 30 // 120 -> 541 // 4 -> 0 // 300 -> 1015 8 AnswersI got the same question... which I solved... but interviewer did not clear the question in the beginning.. now waiting for the response. Got the onsite.. will update after the onsite.. hey, how was your onsite? Show more responses My Mouse and Keyboard are not working, I think it might be the issue with usb port. I am sorry, I didn't meant to comment here!! It was wrong copy & paste error how long does it take to get an answer from Outreach after the onsite? Hi, I am scheduled on HR call . How will it be ? and How shud i prepare for further rounds for coding and behaviour? Hi, What are the questions they ask for new grad software roles? |
See Interview Questions for Similar Jobs
- Software Engineer
- Software Developer
- Java Developer
- Technical Lead
- Software Development Engineer
- Associate Software Engineer
- Consultant
- Software Development Engineer II
- Senior Consultant
- Project Manager
- Senior Software Developer
- Business Analyst
- Analyst
- Senior Engineer
- Associate
- Software Engineer II
- Applications Developer
- Senior Software Development Engineer
- Manager