Opening the reading…
Opening the reading…
BINARY SEARCH › INTRODUCTORY PROBLEMS
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →Suppose you choose a paper at index i as the first paper counted toward the h-index. There are n - i papers from i through the end, and because citations is sorted, every one of them has at least citations[i] citations. This suffix supports an h-index of n - i exactly when citations[i] >= n - i.
As i moves right, citations[i] never decreases while n - i decreases. Therefore the condition citations[i] >= n - i can change only once: it is false for a prefix and true for the remaining suffix. The answer comes from the first true index left, because that index leaves the largest qualifying suffix, so the h-index is n - left. If no index is true, left becomes n and the answer is zero.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(log n) | Each comparison discards either the left half or the right half of the remaining index interval. The interval therefore shrinks by about half per iteration, and no index is scanned separately. |
| Space | O(1) extra | The algorithm stores only n, left, right, and mid; the returned h-index is a single integer and is output rather than working memory. The bound stays constant even for the worst citation distribution, including all zeros or all very large values. |
#include <vector>
using namespace std;
class Solution {
public:
int hIndex(vector<int>& citations) {
int n = citations.size();
int left = 0;
int right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (citations[mid] >= n - mid) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return n - left;
}
};The important placement is the true branch: a qualifying mid is not the answer yet, because an earlier index may qualify and produce a larger suffix. Moving right leftward preserves mid as a possible boundary while searching for the first true position. After the loop, left is either that boundary or n when no paper qualifies, and n - left handles both cases without a special final scan.