Facebook Interview Question
Software EngineersCountry: United States
Interview Type: In-Person
Implemented above algo and using binary search
public static int getHIndex2(Integer[] arr){
Arrays.sort(arr,Collections.reverseOrder()); // O(nLog(n))
int h = 0;
int low=0;
int high=arr.length-1;
//log(n)
while(low<=high){
int mid = (low+high)/2;
if(arr[mid] >= mid+1){
h=mid+1;
low=mid+1;
}else{
high=mid-1;
}
}
return h;
}
#include<stdio.h>
int hIndex(int V[], int len) {
int h = 0;
for(int i=0; i<len; i++) {
if(V[i]>=i+1)
h=i+1;
}
return h;
}
int main() {
int N[] = {1, 1, 1, 1, 1, 1, 1, 1};
printf("H Index: %d\n", hIndex(N, 8));
return 0;
}
We know that if we order the array from largest values to smallest values, that we can keep basically incrementing h values until we get to a number that is smaller than its current index- Since bigger numbers have more flexibility in being considered in the h-index count.
public int getH(int[] arr) {
int h = 0;
for (int i = 0; i >= 0 && arr[i] >= i + 1; i--) {
if (arr[i] >= i + 1) {
h++;
}
}
return h;
}
You have to find an index i , such that all indexes from 0 to i have ValueAt(i) >=i. Since array is sorted this can be done with binary search in log(n) time.
#include<iostream>
#include<stdlib>
using namespace std;
int findHIndex(int * a, int start, int end)
{
int mid = start+end /2;
if(a[mid] == mid) //last point for H index search
return mid;
if(mid == start)
return -1;
else if (a[mid] > mid) // h is to the right of this point
{
findHIndex(a,mid+1,end);
}
else //h is to the left of this point
{
findHIndex(a,start,mid-1);
}
}
// Solution based on binary search approach. Time complexity O(log n)
public static void hIndex(int[] array) {
int length = array.length;
int h = hIndex(array, 0, length-1, 0);
System.out.print(h);
}
public static int hIndex(int[] array, int start, int end, int h) {
if(start > end)
return h;
int mid = (start+end)/2;
if(array[mid] >= array.length-mid)
return hIndex(array, start, mid-1, array.length-mid);
else
return hIndex(array, mid+1, end, h);
}
int search_hindex(int *input, int start, int end, int hindex)
{
int half =0, found = 0;
if (start > end)
return hindex;
half = start + (end - start)/2;
if (half + 1 > input[half])
{
hindex = half + 1;
found= search_hindex(input, start, half -1, hindex);
} else {
found = search_hindex(input, half+1, end, hindex);
}
return found;
}
int compute_hindex(int* input, int length)
{
int hindex = 0; //not found
hindex = search_hindex(input, 0, length-1, hindex);
if (hindex ==0)
hindex = length;
else
hindex--;
return hindex;
}
Using Binary search you should look for the first V[i] that is lower than i+1.
- Demo April 18, 2015Assume the array with indices 0..n is sorted with the greatest number on the left. Then look in the middle and if V[i] < i+1 then memoize this as a minimum found and look in the left side of the rest of array, otherwise don't memoize and look in the right side until you will get to array of length 1. Then the result is memoized-1.