H-Index II
Medium · Binary Search · Explanation and code example
Binary Search for the First Valid Position
How it works
At sorted index i, there are n - i papers with citations at least citations[i]. The condition citations[i] >= n - i becomes true monotonically as i increases. Find its first true position and return n minus that position.
Steps
- Binary search indices in the half-open range [0, n).
- Move right toward the first position with citations[mid] + mid >= n.
- Return n - left.
Complexity
- Time: O(log n).
- Space: O(1).
Things to watch for
- The input must already be sorted.
- Allow the search to end at n, meaning h = 0.
- Use >= so equality is valid.
Python code example
class Solution:
def hIndex(self, citations: list[int]) -> int:
n = len(citations)
left, right = 0, n
while left < right:
mid = (left + right) // 2
if citations[mid] + mid >= n:
right = mid
else:
left = mid + 1
return n - left
C++ code example
class Solution {
public:
int hIndex(vector<int>& citations) {
const int n = citations.size();
int l = 0;
int r = n;
while (l < r) {
const int m = (l + r) / 2;
if (citations[m] + m >= n)
r = m;
else
l = m + 1;
}
return n - l;
}
};
Source and license
Explanation by LC Tracker. Code adapted from walkccc / Peng-Yu Chen · MIT license. Node types are supplied by LeetCode where needed.