# Senior Engineer Interview Questions

Senior engineer interview questions shared by candidates

## Top Interview Questions

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

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...

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. 8 AnswersO(size of array) time & space: First, realize that saying the element should be the product of all other numbers is like saying it is the product of all the numbers to the left, times the product of all the numbers to the right. This is the main idea. Call the original array A, with n elements. Index it with C notation, i.e. from A[0] to A[n - 1]. Create a new array B, also with n elements (can be uninitialized). Then, do this: Accumulator = 1 For i = 0 to n - 2: Accumulator *= A[i] B[i + 1] = Accumulator Accumulator = 1 For i = n - 1 down to 1: Accumulator *= A[i] B[i - 1] *= Accumulator Replace A with B It traverses A twice and executes 2n multiplicates, hence O(n) time It creates an array B with the same size as A, hence O(n) temporary space # A Python solution (requires Python 2.5 or higher): def mult(arr, num): return reduce(lambda x,y: x*y if y!=num else x, arr) arr = [mult(arr,i) for i in arr] # O(n^2) time, O(n) space Create two more arrays. One array contains the products of the elements going upward. That is, B[0] = A[0], B[1] = A[0] * A[1], B[2] = B[1] * A[2], and so on. The other array contains the products of the elements going down. That is, C[n] = A[n], C[n-1] = A[n] * A[n-1], and so on. Now A[i] is simply B[i-1] * C[i+1]. Show More Responses def without(numbers): lognums = [math.log10(n) for n in numbers] sumlogs = sum(lognums) return [math.pow(10, sumlogs-l) for l in lognums] 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) #include #define NUM 10 int main() { int i, j = 0; long int val = 1; long A[NUM] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Store results in this so results do not interfere with multiplications long prod[NUM]; while(j < NUM) { for(i = 0; i < NUM; i++) { if(j != i) { val *= A[i]; } } prod[j] = val; i = 0; val = 1; j++; } for(i = 0; i < NUM; i++) printf("prod[%d]=%d\n", i, prod[i]); return 0; } void fill_array ( int* array, size ) { int i; int t1,t2; t1 = array[0]; array[0] = prod(1, size, array ); for(i = 1; i < size; i++){ t2 = array[i]; array[i] = prod(i, array.size(), array)*t1; t1 *= t2; } int prod(start, end, array){ int i; int val(1); for(i = start; i < end; i++ ) val *= array[i]; return val; } Hello, Thank you for sharing your interview experience. As a small team of ex-Google employees, we have recently launched a new website, interviewjoy.com, where you can earn money by sharing your interview experiences/insights with other job candidates. (It is a marketplace for sharing job interview insights). Posting an interview consultancy service is totally free & anonymous and we are giving 50 USD sign-up bonus for the first 500 users. You are kindly invited to interviewjoy.com to check it out. Users already started making money on the website! Best Regards.. (For more information: onboarding@interviewjoy.com) |

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

What sort would you use if you required tight max time bounds and wanted highly regular performance. 6 AnswersVector sort. Guaranteed to be O(n log n) performance. No better, no worse. That is so say, a "Balanced Tree Sort" is guaranteed to be O(n log n) always. Show More Responses Merge sort and heapsort are always guaranteed to be n*log(n). Quicksort is usually faster on the average but can be as bad as O(n^2), although with very low probability. Heapsort also does it sorting in-place, without needing an extra buffer, like mergesort. Lastly, heapsort is much easier to implement and understand than balancing trees mentioned by earlier posts. for something like this you generally want bubble sort or insertion sort. It's not about being fast it's about being consistent. Make it do exactly the same thing every time. Use a sorting network. There's some precomputation time, but runtime will be very consistent (the only variability is branch prediction performance) |

What has been your active role in the team process you're currently working with? 2 AnswersExplained details of daily involvement, software used, level of completion of initial input received, and final deliverable. I quote the repairs and write up the job router steps to include R & R parts, inspection. Testing, and FAA 8130 |

### Senior Network Engineer at CSC was asked...

What are the 6 TCP flags? 2 AnswersGOOGLE EM URG, RST, PSH, CWR, SYN, FIN, ACK, ECN |

What sort of anomalies would you look for to identify a compromised system? 1 AnswerI used a whiteboard to draw out a basic network architecture including security technologies like IPS/IDS, Firewalls, AV, etc, and described the type of traffic and logs I could use to identify a compromised system. |

### Senior RF Engineer at Nexius was asked...

What will be the greatest contribution that you can ever make as an individual to your team 1 Answercoalescing my individual knowhow with overall experience that my team has makes for a well-rounded team that knows esprit de corps and can work towards success all the times |

### 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. 30 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). var nums = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; var newnums = new int[nums.Length]; for (var i = 0; i index != i).Aggregate((a, b) => a*b); } 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...) |

Coderpad: given an array scores[][] = {“jerry”,”65”},{“bob”,”91”}, {“jerry”,”23”}, {“Eric”,”83”}} Find the student with highest average score 14 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 Use a DataType Student (name, avg) to return the student with max avg. Follow this logic. 1. Iterate through the 2D array - get one student array at a time, student[0] is name, student[0] is grade . 2. If student doesn't exist in map (map of String, and ArrayList), then a. create new integer list and add this student's grade to it, b. add student to map. c. re-calculate max 3. If student exists, a. get student's grades list from map b. add current grade to list c. add student and updated grades list to map d. calculate student's avg e. re-calculate max. 4. Return the max student. JAVA Code at: https://github.com/vinayakolhapure/Interview/blob/master/src/com/src/practice/StudentWithMaxAvg.java 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); } } |

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. |

**1**–

**10**of

**13,265**Interview Questions

## See Interview Questions for Similar Jobs

- Software Engineer
- Software Developer
- Software Development Engineer
- Staff Software Engineer
- Director
- Principal Software Engineer
- Senior Software Developer
- Product Manager
- Software Engineer III
- Senior Software Development Engineer
- Data Scientist
- Intern
- Project Manager
- Vice President
- Manager
- Software Development Engineer II
- Engineering Manager
- Engineer
- Java Developer