A researcher's papers are listed by how often each was cited: citations[i] is the count for paper i, and the array is sorted from smallest to largest.
Return the researcher's h-index: the largest number h such that h of the papers have been cited at least h times each. Your algorithm should take logarithmic time.
Example 1
Input: citations = [1, 2, 4, 6, 8, 9] Output: 4 Why: 4, 6, 8 and 9 are four papers with at least 4 each
2 more examples and the constraints
Example 2
Input: citations = [0, 0, 0] Output: 0 Why: no paper has a single citation
Example 3
Input: citations = [3, 5, 7] Output: 3 Why: all three papers have at least 3
Constraints
- 1 ≤ number of papers n ≤ 100,000
- 0 ≤ citations[i] ≤ 1,000
- citations is sorted in ascending order
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Linear scanO(n)
- Binary searchO(log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Checks for 100,000 papers | Verdict |
|---|---|---|---|
| Linear scan | O(n) | Correct; misses the log bound | |
| Binary search | O(log n) | Best; about 17 checks |
n = number of papers.
Edge cases to test
- No citations at all. [0, 0, 0] gives 0: no index passes and
loends at n. - One paper. [0] gives 0 and [100] gives 1: h can never exceed the number of papers.
- Every paper counts. [3, 5, 7] gives 3, from index 0.
- Repeated values. [2, 2, 2, 2] gives 2; equal values do not break the sorted test.
Common mistakes
- Returning
citations[i]instead ofn − i; the h-index counts papers, not citations. - Using
>instead of≥, which misses papers cited exactly h times. - Returning
n − midfrom inside the loop at the first passing mid, which may not be the first passing index.
How to talk through it
- 1Clarify. Sorted ascending, right? Can a paper have 0 citations? What if no paper is cited?
- 2Turn h into a test. The last
n − ipapers all have at leastcitations[i], so h =n − iworks whencitations[i] ≥ n − i. - 3Give the scan. First index that passes, O(n). Note that the test flips only once.
- 4Binary search. Find the first passing index; say what
lomeans when the loop ends. - 5Test out loud. Run the all-zero case and a single paper with many citations.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?