Google Interview Question
1,223 Interview Reviews |
Back to all Google Interview Questions & Reviews
Interview questions and reviews posted anonymously by interview candidates
Interview Question for Intern at Google:
Helpful Question?
Yes |
No
Inappropriate?
Answers & Comments (5)
1 of 1 people found this helpful
Better answer: run binary search again twice once you have found the number the first time. For the upper half and the lower half - so total run time is O(logN)
Helpful Answer?
Yes |
No
Inappropriate?
Helpful Answer?
Yes |
No
Inappropriate?
import java.util.HashMap;
public class FindOccurrences {
/**
* @param args
*/
public static void main(String[] args) {
int unsortedArray[] = {4,6,7,8,4,5,6,8,3,2,4,5,7,8,9,3,4,6,7,8};
System.out.println(findOccurrencesUnsorted(unsortedArray,8));
int sortedArray[] = {1,2,2,3,3,3,4,4,4,4,5,5,5,5,5};
System.out.println(findOccurrencesSorted(sortedArray,5));
}
private static int findOccurrencesUnsorted(int[] array, int number)
{
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<array.length;i++)
{
if(map.get(array[i])==null)
map.put(array[i],1);
else
{
int count = map.get(array[i]);
count++;
map.remove(array[i]);
map.put(array[i],count);
}
}
return map.get(number);
}
private static int findOccurrencesSorted(int[] array, int number)
{
int counter = 0;
for(int i=0;i<array.length;i++)
{
if(array[i]!=number)
continue;
else
counter++;
}
return counter;
}
}
Helpful Answer?
Yes |
No
Inappropriate?
//inputs are the sorted array, k is the number looking for
//start and end are two index values, main method calls with (start=0) and (end=length-1)
int GetOccurance(int[] inputs, int k, int start, int end)
{
if(start<end) return 0;
if(inputs[end]<k||inputs[start]>k) return 0;
if(inputs[start]==k&&inputs[end]==k) return end-start+1;
int mid = (start+end)/2;
if(input[mid]<k)
return GetOccurance(inputs, k, mid+1, end);
else if(input[mid]>k)
return GetOccurance(inputs, k, start, mid-1);
else
return GetOccurance(inputs, k, start, mid-1)+1+GetOccurance(inputs, k, mid+1, end);
}
Helpful Answer?
Yes |
No
Inappropriate?
To comment on this
question,
Sign In with Facebook or
Sign Up
0 of 0 people found this helpful
by Interview Candidate: