Last updated on January 5th, 2025 at 01:11 am
Here, we see a H-Index LeetCode Solution. This Leetcode problem is solved using different approaches in many programming languages, such as C++, Java, JavaScript, Python, etc.
List of all LeetCode Solution
Topics
Hash-Table, Sort
Companies
Bloomberg, Facebook, Google
Level of Question
Medium
H-Index LeetCode Solution
Table of Contents
1. Problem Statement
Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper, 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.
Example 1:
Input: citations = [3,0,6,1,5]
Output: 3
Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 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,3,1]
Output: 1
2. Coding Pattern Used in Solution
The coding pattern used in these implementations is Counting/Sorting-Based Search or Modified Binary Search (depending on the implementation).
3. Code Implementation in Different Languages
3.1 H-Index C++
class Solution { public: int hIndex(vector<int>& citations) { return hIndexBruteForce(citations); } int hIndexBruteForce(vector<int>& c) { sort(c.begin(), c.end()); int n = c.size(); int maxi = 0; for(int i = 0; i < n; i++) { if(c[i] >= n - i) { maxi = max(maxi, n - i); } } return maxi; } };
3.2 H-Index Java
class Solution { public int hIndex(int[] citations) { int low=0 , high = citations.length; while(low < high){ int mid = (low+high+1)/2; int cnt=0; for(int i=0 ; i<citations.length ; i++) if(citations[i] >= mid) cnt++; if(cnt >= mid) low = mid; else high = high=mid-1; } return low; } }
3.3 H-Index JavaScript
var hIndex = function(citations) { citations.sort((a,b)=>b-a) let i=0 while(citations[i]>i) i++ return i };
3.4 H-Index Python
class Solution(object): def hIndex(self, citations): n = len(citations) papers = [0] * (n + 1) for c in citations: papers[min(n, c)] += 1 i = n s = papers[n] while i > s: i -= 1 s += papers[i] return i
4. Time and Space Complexity
Time Complexity | Space Complexity | |
C++ | O(n log n) | O(1) |
Java | O(n log n) | O(1) |
JavaScript | O(n log n) | O(1) |
Python | O(n) | O(n) |