Compute the H-Index From Citation Counts

medium array counting sort

Problem

Given citation counts for a researcher's papers, return the h-index — the largest h such that at least h papers have been cited at least h times each. The clean linear-time approach: bucket each paper by its citation count, capping at n (any count above n is the same as n since you can't have more than n papers). Then walk buckets from n down to 0, accumulating the running tally of papers with at least that many citations. The first bucket where that tally is at least the bucket index is the h-index.

Inputcitations = [3, 0, 6, 1, 5]
Output3
3 papers have ≥ 3 citations (the ones with 3, 6, 5). No 4 papers have ≥ 4 citations. So h = 3.

def h_index(citations):
    n = len(citations)
    buckets = [0] * (n + 1)
    for c in citations:
        buckets[min(c, n)] += 1
    count = 0
    for h in range(n, -1, -1):
        count += buckets[h]
        if count >= h:
            return h
    return 0
function hIndex(citations) {
  const n = citations.length;
  const buckets = new Array(n + 1).fill(0);
  for (const c of citations) buckets[Math.min(c, n)]++;
  let count = 0;
  for (let h = n; h >= 0; h--) {
    count += buckets[h];
    if (count >= h) return h;
  }
  return 0;
}
class Solution {
    public int hIndex(int[] citations) {
        int n = citations.length;
        int[] buckets = new int[n + 1];
        for (int c : citations) buckets[Math.min(c, n)]++;
        int count = 0;
        for (int h = n; h >= 0; h--) {
            count += buckets[h];
            if (count >= h) return h;
        }
        return 0;
    }
}
int hIndex(vector<int>& citations) {
    int n = citations.size();
    vector<int> buckets(n + 1, 0);
    for (int c : citations) buckets[min(c, n)]++;
    int count = 0;
    for (int h = n; h >= 0; h--) {
        count += buckets[h];
        if (count >= h) return h;
    }
    return 0;
}
Time: O(n) Space: O(n)