Given an array of integers citations
where citations[i]
is the number of citations a researcher received for their i-th
paper, and citations
is sorted in an ascending order, return the researcher’s h-index.
The h-index is defined as the maximum value h
such that the researcher has published h
papers that have each been cited at least h
times.
citations
is sorted in ascending order?
Given that the array is sorted, a binary search approach would work efficiently. The typical strategy for finding the h-index in a sorted array is:
left
at the start (0) and right
at the end (len(citations) - 1
) of the array.mid
as the average of left
and right
.>= citations[mid]
by n - mid
(where n
is the total number of papers).citations[mid]
is a valid h-index by comparing it to n - mid
.left
exceeds right
.The time complexity of the binary search approach is (O(\log n)), where n
is the number of papers.
def hIndex(citations):
n = len(citations)
left, right = 0, n - 1
while left <= right:
mid = (left + right) // 2
if citations[mid] == n - mid:
return citations[mid]
elif citations[mid] < n - mid:
left = mid + 1
else:
right = mid - 1
return n - left
# Example usage:
citations = [0, 1, 3, 5, 6]
print(hIndex(citations)) # Output: 3
In this code, the binary search helps efficiently find the h-index by narrowing down the potential values based on the sorted order of the citations array.
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?