Problem 275

Abstract / Summary

Given a sorted array of citations, find the highest h index where at least h papers have at least h citations each.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0275.cpp

class Solution {
public:
    int hIndex(vector<int>& citations) {
        reverse(citations.begin(), citations.end());
        int h = 0;
        while (h < citations.size())
        {
            if (citations[h] <= h)
                break;
            h++;
        }

        return h;
    }
};
15 lines | 313 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 40% (600k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Binary Search
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the h-index for a list of citation counts. It first reverses the input vector, then iterates from the beginning while a simple condition holds, and finally returns the count of iterations performed. The algorithm is concise, operates in-place on the input, and stops as soon as the stopping condition is met, which avoids unnecessary work.

Key Steps

The first logical operation is the reversal of the citation array. By reversing, the algorithm aligns the smallest citation counts at the front of the vector, which simplifies the subsequent linear scan.

reverse(citations.begin(), citations.end());

After the reversal, a counter h is initialized to zero. This counter will ultimately represent the h-index.

int h = 0;

The core of the algorithm is a while loop that continues as long as h is less than the size of the vector. Inside the loop, the citation at position h is compared with the current value of h. If the citation count is less than or equal to h, the loop terminates; otherwise, h is incremented.

while (h < citations.size())
{
    if (citations[h] <= h)
        break;
    h++;
}

When the loop exits, the current value of h is returned as the computed h-index.

return h;

Edge Cases Handled

When the input vector is empty, the reversal operation is a no-op, and the loop condition h < citations.size() evaluates to false immediately. Consequently, h remains zero and the function returns zero, which is the correct h-index for an empty set of papers.

If all citation counts are zero, after reversal the vector still contains only zeros. The first iteration checks citations[0] <= 0, which is true, causing an immediate break and returning zero. This correctly reflects that no paper has any citations.

When every paper has a citation count larger than the total number of papers, the loop will increment h until it reaches the size of the vector. At that point the condition h < citations.size() fails, the loop ends, and the function returns the total number of papers, which is the maximum possible h-index for the dataset.

If the citation counts are already sorted in descending order, the reversal step transforms them into ascending order, ensuring that the smallest values are examined first. The loop then stops precisely at the point where the citation count ceases to exceed the current h, yielding the correct index without additional sorting.

Performance Optimizations

The algorithm performs an in-place reversal using the standard library reverse, which swaps elements without allocating extra storage. This choice eliminates the need for a separate copy of the data and keeps memory usage minimal.

The linear scan uses a single counter and a direct index access, avoiding any auxiliary data structures. The early-exit condition if (citations[h] <= h) break; ensures that the loop stops as soon as the h-index condition fails, preventing unnecessary iterations once the result is determined.

By combining the reversal and the single pass, the implementation achieves the desired result with a minimal number of operations and without extra overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a big pile of drawings that you made for your friends. Some of your drawings are super famous and get lots of gold stars, while others have fewer reach. The goal here is to find a special number called the h-index. This number tells you how many of your drawings have at least that many gold stars.

First, the computer takes your pile of drawings and sorts them so the ones with the most stars are right at the very front. After that, it starts counting through the pile one by one. It looks at the number of stars on each drawing to see if that drawing is still famous enough to keep the count going. As long as the number of gold stars remains higher than the drawing's position in line, it keeps counting higher and higher. Once it finds a drawing that does not have enough stars to keep up with the line, it stops and tells you the final count.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.07 | σ = 2.18

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
fengvyi C++
fpdjsns C++
fsq C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fengvyi C++
fpdjsns C++
fsq C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
MacJim C++
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
wisdompeak C++
XiaotaoGuo C++
YuriSpiridonov Python
48 links | 32 authors | 9 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

40 easy 30 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality