275. H-Index II LeetCode Solution

In this guide, you will get 275. H-Index II LeetCode Solution with the best time and space complexity. The solution to H-Index II problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. H-Index II solution in C++
  4. H-Index II solution in Java
  5. H-Index II solution in Python
  6. Additional Resources
275. H-Index IILeetCode Solution image

Problem Statement of H-Index II

Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations is sorted in ascending order, return the researcher’s h-index.
According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times.
You must write an algorithm that runs in logarithmic time.

Example 1:

Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3.

Example 2:

Input: citations = [1,2,100]
Output: 2

Constraints:

n == citations.length
1 <= n <= 105
0 <= citations[i] <= 1000
citations is sorted in ascending order.

Complexity Analysis

  • Time Complexity: O(\log n)
  • Space Complexity: O(1)
See also  986. Interval List Intersections LeetCode Solution

275. H-Index II LeetCode Solution in C++

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;
  }
};
/* code provided by PROGIEZ */

275. H-Index II LeetCode Solution in Java

class Solution {
  public int hIndex(int[] citations) {
    final int n = citations.length;
    int l = 0;
    int r = n;

    while (l < r) {
      final int m = (l + r) / 2;
      if (citations[m] + m >= n)
        r = m;
      else
        l = m + 1;
    }

    return n - l;
  }
}
// code provided by PROGIEZ

275. H-Index II LeetCode Solution in Python

class Solution:
  def hIndex(self, citations: list[int]) -> int:
    n = len(citations)
    return n - bisect.bisect_left(range(n), n,
                                  key=lambda m: citations[m] + m)
 # code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.