LeetCode 274: H-Index — Python Solution

LeetCode 274: H-Index is a Medium array / string problem. This Python walkthrough develops a sorting and threshold scan solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicArray / String
Reusable patternsorting and threshold scan
ComplexityO(n log n) time and O(1) auxiliary space aside from sorting

Recognizing the pattern

Array and string questions usually reward a precise index invariant. Decide which prefix or suffix is already final before mutating the next position.

For this problem specifically, sort citations descending and find the largest rank whose citation count is at least that rank. The invariant worth writing beside the code is: The first h sorted papers each have at least h citations.

Step-by-step algorithm

  1. Identify the input state consumed by hIndex(citations) and initialize the data required by the sorting and threshold scan pattern.
  2. Sort citations descending and find the largest rank whose citation count is at least that rank.
  3. After each update, verify the page’s central invariant: The first h sorted papers each have at least h citations.
  4. Finish only after the boundary behavior is covered: The answer can be zero or the number of papers.

Python solution

class Solution:
    def hIndex(self, citations):
        citations.sort(reverse=True)
        answer = 0
        for rank, count in enumerate(citations, 1):
            if count < rank:
                break
            answer = rank
        return answer

Reading the implementation

The main entry point is hIndex(citations). The named working state includes answer; those variables make the sorting and threshold scan state visible instead of hiding it in incidental control flow.

A single main loop advances the algorithm, which is the key reason the traversal does not revisit already resolved input unnecessarily. In concrete terms, sort citations descending and find the largest rank whose citation count is at least that rank.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Sort citations descending and find the largest rank whose citation count is at least that rank. Each update records the current item without invalidating earlier decisions; consequently, the first h sorted papers each have at least h citations.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(n log n) time and O(1) auxiliary space aside from sorting. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

A copied output buffer can simplify reasoning, but the in-place version reduces auxiliary memory when mutation is allowed. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

assert Solution().hIndex([3,0,6,1,5]) == 3

Common mistakes and edge cases

  • Problem-specific boundary: The answer can be zero or the number of papers.
  • Pattern-level pitfall: Do not let a write operation destroy input that a later read still needs; write direction and boundary conventions matter.
  • Invariant check: after every update, confirm that the first h sorted papers each have at least h citations.

Interview review checklist

  • Explain why sorting and threshold scan matches the structure of this input.
  • State the invariant in one sentence before tracing code: The first h sorted papers each have at least h citations.
  • Derive O(n log n) time and O(1) auxiliary space aside from sorting from how many times each element or state is visited.
  • Test the boundary explicitly: The answer can be zero or the number of papers.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 45. Jump Game II · Next: 380. Insert Delete GetRandom O(1)