↳
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. Less
↳
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? Less
↳
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.... Less
↳
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); } } Less
↳
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()); } } Less
↳
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 Less
↳
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; } Less
↳
//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; } Less
↳
X should be equal to Y, right?
↳
The 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. Less
↳
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. Less
↳
@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. Less
↳
int raise(num, power){ if(power==0) return 1; if(power==1) return num; return(raise(num, power-1)*num); } Less
↳
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; } Less
↳
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; } Less
↳
What is taught in compsci, and even what's in Knuth, isn't entirely right on modern out-of-order execution core CPUs Less
↳
void traverse(Node node){ if(node == null) return null; System.out.println(node.data); traverse(node.left); traverse(node.right); } Less
↳
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.. Less
↳
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. Less
↳
sorry, typo while(top>p)
↳
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. Less
↳
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. Less
↳
If you're writing it in ruby def find_repeat(numbers) numbers.length.times{|n| return numbers[n] if numbers[n] != n } end Less
↳
Mat, try 1,2,2,3: 1+2+2+3= 8 1^2^2^3= 2 (8-2)/2=3?2
↳
Can you give an high level solution which you arrived at the end? I am curious to know the solution 😊 Less
↳
The solution was something like: Look for the candidates that have a bigger difference in cost first (in this case B and D since the difference for the price to each office are 400), choose the cheaper option for those. After one of the offices is full then just choose whatever spot is left. Less
↳
I would use a Min Heap for SF of size = no. of candidates / 2 . k = no. of candidates / 2 ; for(int i : SFcosts){ minHeap.offer(i); if(minHeap.size() > k){ minHeap.poll(); } } // so at the end we have half candiates with minimum cost for SF then remaining will go ti NY Less
↳
Depends how big the school bus is, for simplicity, lets say its the small bus that can fit 20 + 1 people. You have to take account of the empty space as well, therefore a person could be sitting in the middle line and three more in the front so we have around 30 people making a full squished bus. The average size of a golf ball is around 3 cm in diameter. The height of the bus is usually 200 cm, the width of an average person is usually 50 cm. The depth of the seat is about 70 cm You can calculate the volume of that cubic form to be 50 x 70 x 200 x 3 x 30 = the number of golf balls in average. Less
↳
Nobody need to actually put golf balls in a school buss , nobody care if the number is 61,000,000 or whatever .Nobody in Google cares how good are you in giving estimates to the size of a buss. The answer is bussWidth*bussHight*bussLength / (ball/Diameter ^ 3 * sin (60) * sin(60) ^2 ) . This answer depends on the size of the school buss, different busses yield different answer. The sin(60) are since its gold balls and not cubics. Less
↳
As Jehova put it. This tests your problem-solving stance being seeing that you leave the right things as variables. The question is really about trigonometry and understanding how tightly you can pack spheres. In other words, you need to figure the effective volume of each golf ball. To do so, first consider a single plane of balls, and a single row from it. If the ball radius is r, the width required for each ball is 2r. Now consider the depth required by each row. Since the rows will be "staved off" from each other, each row requires somewhat less than 2r for its depth. In fact, each requires r * tan 60, or about 1.73 * r. To see why, notice that each adjacent group of three spheres forms a triangle, and, because of the symmetry of the situation, their centers form an equilateral triangle. Thus each of its angles it 60 degrees. Since tan(theta) = opposite / adjacent, we have that tan(60) = depth / radius, or depth = radius * tan(60). Finally, consider the height require by each plane of balls. Take the three adjacent balls from the first plane and imagine adding a forth ball above them in the center. The centers of the four balls now form a tetrahedron (just a pyramid with a triangular base). We need to find the height from the center of the base of the tetrahedron to its top vertex. Looking at a diagram, one can see that the distance to the center of the base from one of the base vertices is found by cos(theta) = radius / hypotenuse, or cos(30) = r / distance, meaning distance = r / cos(30), or about 1.15 * r. If you create a line going from the base vertex to the base center, it then becomes clear that this line forms a vertical isosceles right triangle with the height line. In other words, the distance we just found is equal to the height of the tetrahedron. Bring it all together, we have that the effective volume of each ball is: effectiveWidth * effectiveDepth * effectiveHeight = 2r * r tan 60 * r / cos 30. So finally, the number of balls is the bus volume divided by each ball's effective volume. Less