274. H-Index

Dare2Solve

Dare2Solve

274. H-Index
SAMSUNG 49-Inch Odyssey G9
SAMSUNG 49-Inch Odyssey G9
Because earth is not flat

Intuition

The h-index is a metric that aims to measure both the productivity and citation impact of a researcher's publications. To find the h-index, we need to determine the maximum value h such that the researcher has at least h papers with h or more citations.

Approach

  1. Sort the citations: Start by sorting the array of citations in ascending order.
  2. Initialize a counter: Use a counter h to keep track of the h-index value.
  3. Iterate through the sorted citations:
    • For each citation citations[i], check if it meets the condition citations[i] >= length - i.
    • If the condition is met, increment the h-index counter h.
  4. Return the h-index: The final value of h after the loop will be the h-index.

Complexity

Time Complexity

Thus, the overall time complexity is O(n log n).

Space Complexity

Code

C++

class Solution
{
public:
    int hIndex(vector<int>& citations) 
    {
        sort(citations.rbegin(),citations.rend());
        int n=citations.size();
        int i;
        for(i=0;i<n;i++)
        {
            if(citations[i]>=(i+1))
            {
                continue;
            }
            else
            {
                break;
            }
        }
        return i;
    }
};

Python

class Solution:
    def hIndex(self, citations: List[int]) -> int:
        citations.sort()
        
        h = 0
        length = len(citations)
        
        for i in range(length):
            item = citations[i]
            if item >= length - i:
                h += 1
        
        return h

Java

import java.util.Scanner;
class Solution {
    public int hIndex(int[] citations) {
        sortArray(citations);
        int n = citations.length;
        for (int i = 0; i < n; i++) {
            int h = n - i;
            if (citations[i] >= h) {
                return h;
            }
        }
        return 0;
    }
    private void sortArray(int[] arr) {
        int n = arr.length;
        int min=0;
       for(int i=0;i<n-1;i++){
        min=i;
        for(int j=i+1;j<n;j++){
            if(arr[j]<arr[min]){
                min=j;
            }
        }
        int temp=arr[min];
        arr[min]=arr[i];
        arr[i]=temp;
       }
}
}

JavaScript

/**
 * @param {number[]} citations
 * @return {number}
 */
var hIndex = function (citations) {
    citations.sort((a, b) => a - b);

    let h = 0;
    const length = citations.length;

    for (let i = 0; i < length; i++) {
        const item = citations[i];
        if (item >= length - i) {
            console.log(i, item, length - i);
            h++;
        }
    }

    return h;

};