H-Index II

H-Index II (LeetCode 275): binary search on sorted citations to find the h-index in O(log n).

Problem Statement

Given citations sorted in ascending order, compute the researcher’s h-index: the largest h such that h papers each have at least h citations. Must run in O(log n).

Example

Input:  citations = [0,1,3,5,6]
Output: 3

Approach

For index mid, there are n - mid papers with at least citations[mid] citations. If citations[mid] >= n - mid, a larger h-index may lie to the left; otherwise go right. The answer is n - lo after the search.

Complexity

  • Time: O(log n)
  • Space: O(1)

Solution Code

Python

def hIndex(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

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

C++

int hIndex(vector<int>& citations) {
    int n = citations.size(), lo = 0, hi = n - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (citations[mid] >= n - mid) hi = mid - 1;
        else lo = mid + 1;
    }
    return n - lo;
}

Key Takeaways

  • Key relation: n - mid papers have >= citations[mid] citations.
  • Because the array is pre-sorted, the search is O(log n) (vs O(n) for H-Index I).
  • Reference: LeetCode 275 (H-Index II).
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.