H-Index II

Medium Binary SearchArray

Problem

Given citations sorted ascending, return the h-index — the max h with at least h papers each cited ≥ h times. O(log n).

Example 1 Input: [0,1,3,5,6] Output: 3
Example 2 Input: [1,2,100] Output: 2

Constraints

Approach — Binary Search

This is a Binary Search problem. The idea: repeatedly halve the search space, discarding the half that can't contain the answer. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(log n) time.

Solution code

Python

class Solution:
    def hIndex(self, citations):
        n = len(citations)
        lo, hi = 0, n - 1
        while lo <= hi:
            mid = (lo + hi) // 2
            if citations[mid] >= n - mid:
                hi = mid - 1
            else:
                lo = mid + 1
        return n - lo

Java

class Solution {
    public int hIndex(int[] c) {
        int n = c.length, lo = 0, hi = n - 1;
        while (lo <= hi) {
            int m = lo + (hi - lo) / 2;
            if (c[m] >= n - m) hi = m - 1;
            else                lo = m + 1;
        }
        return n - lo;
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve H-Index II interactively → ← All solutions