See full Google Software Engineer Interview or all Google Interviews
Interview Question for Software Engineer at Google: |
Oct 19, 2009 |
The implementation question: Find a max and min in an array simaltaneously. I used a 2n comparisons approach and a 1.5n on-average approach.
Helpful Question?
Yes |
No
Answers & Comments (6)
0 of 1 people found this helpful
Helpful Answer?
Yes |
No
Inappropriate?
please do not keep misleading others, divide and conquer will lead u O(nlogn).
Helpful Answer?
Yes |
No
Inappropriate?
a complete sorting using divide and conquer will lead to worst case O(nlogn).
however, in this case, the merging steps can be simplified to just two comparisons, thus allowing the worst case performance to be 1.5n. i have the algorithm implemented in java. you can try it out. for the merging step, just check the first and last elements of the 2 sub arrays and do swaps.
Helpful Answer?
Yes |
No
Inappropriate?
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i = 0; i < a.length; i++{
if (a[i] > max) {
max = a[i];
}
else if (a[i] < min)
min = a[i];
}
}
Is this the 2n approach? O(2n) = O(n)....
What am I missing?
Helpful Answer?
Yes |
No
Inappropriate?
int tempMin, tempMax;
int max = a[0];
int min = a[0];
for (int i = 1; i < n-1; i = i+2){
if (a[i] <= a[i+1]){
tempMin = a[i];
tempMax = a[i+1];
}
else {
tempMin = a[i+1];
tempMax = a[i];
}
if (tempMax > max) {
max = tempMax;
}
if (tempMin < min) {
min = tempMin;
}
}
if (n % 2 == 0) { // Do this if there are an even number of elements
if (a[n-1] < min) min = a[n-1];
else if (a[n-1] > max) max = a[n-1];
}
Helpful Answer?
Yes |
No
Inappropriate?
0 of 0 people found this helpful
by Interview Candidate: