There is this really good interview question that I encountered somewhere recently and I wanted to ask you all geniuses what can be the most optimized solution for this. So the question is as follows : Given an array of integers, find a maximum number n such that there are atleast n array elements which are greater than n. The input array is unsorted.
e.g. :
Input : 1,2,5,7,8,10 Output : n = 4
Input : 0,2,7,8,19,5,45,9,23 Output : n = 6
One solution I could think of(if the array is sorted case) is a sequential scan of all elements in the array to find out min:n and max:n. Then increment integers between min:n to max:n and check out one by one. But this is O(N) solution. Can somebody suggest a better one ?
e.g. : for input 1 min:n = 2 and max:n = 5
then you would check for numbers 2,3 and 4 as the answer.
As from the answers, if the array is unsorted there is no better than O(N) solution. But the next question is what if the given array is sorted ?
pseudocode :
// this assumes sorted input.
pubic int findhighestIndex(List<Integer> input){
it min=0,max=0,n=0,maxIndex=0;
for(int i=0;i<input.size();i++){
if( input.get(i)>(input.size()-i) ){
max=input.get(i);
maxIndex=i;
min=input.get(i-1);
break;
}
else if(input.get(i)<(input.size()-i)){
max=min=input.get(i);
}
}
int i=max;
while( i>=min && (input.size()-maxIndex)<i ){
i--;
}
System.out.println(i);
}
Update : This problem is also known as finding h-index