H-Index
LeetCode 274 · Medium · solution, intuition & step-by-step walkthrough
Sorted descending, h = first i where citations[i] ≤ i.
This is how I solved H-Index (LeetCode 274), a medium problem from the Counting Sort pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Sort citations from most to least. Walking down the list, paper i (0-based) still supports an h of i+1 as long as it has more than i citations; the first paper that doesn't stops the count.
Approach
- 1
Sort descending.
- 2
Advance i while citations[i] > i.
- 3
Return i.
How I solved it
Sort descendingPythonO(n log n) time
class Solution:
def hIndex(self, citations: List[int]) -> int:
citations.sort(reverse=True)
i=0
while i<len(citations):
if not citations[i]>i:
#6,5,3,1,0 -->citations
#0,1,2,3,0 -->index
break
i+=1
return iH-Index — FAQ
What is the intuition behind H-Index?
Sort citations from most to least. Walking down the list, paper i (0-based) still supports an h of i+1 as long as it has more than i citations; the first paper that doesn't stops the count.
How do you solve H-Index (LeetCode 274)?
1. Sort descending. 2. Advance i while citations[i] > i. 3. Return i.
What is the time and space complexity of H-Index?
Time: O(n log n). Space: O(1). (Accepted approach: Sort descending.)
What are common mistakes in H-Index?
A counting-sort version gives O(n).