Imagine you have a sorted array of integers citations where citations[i] represents the number of citations a researcher has received for their i-th paper. Your task is to compute the researcher’s h-index.
The h-index is defined as follows:
index h if h of their N papers have at least h citations each, and the other N-h papers have no more than h citations each.Given that the citations array is sorted in ascending order, design an algorithm to compute the h-index.
You must write an efficient algorithm with a time complexity less than or equal to O(log N).
h-index should be 0.With these clarifications, we’re ready to devise a solution.
Given the array is sorted, we can leverage binary search to find the h-index efficiently. The idea is to factor in the position of each paper in the array relative to its citation count, given the definition of the h-index.
left and right) to represent the start and end of the array.h-index.h-index criteria.Here is the C++ implementation:
#include <vector>
using namespace std;
class Solution {
public:
int hIndex(vector<int>& citations) {
int n = citations.size();
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
// Number of papers with at least citations[mid] citations is (n - mid)
if (citations[mid] == n - mid) {
return citations[mid];
} else if (citations[mid] < n - mid) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return n - left;
}
};
left to 0 and right to the last index of the array.left exceeds right:
mid index satisfies the condition of the h-index (i.e., there are at least n - mid papers with citations[mid] or more citations).citations[mid].citations[mid] is less than n - mid, it means there are not enough papers with at least mid citations, move the left pointer to mid + 1.right pointer to mid - 1.n - left, which will be the h-index.O(log N) time because it uses binary search.O(1) since we are using a constant amount of extra space.This efficient approach ensures that the h-index is computed quickly even for large arrays.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?