Top Interview 150
Understanding the h-index is critical in academic research metrics and makes for an interesting problem in algorithm design. Letβs explore how to solve LeetCode 274: H-Index effectively in JavaScript.
π Problem Description
Given an array citations, where citations[i]
is the number of citations a researcher received for their th
paper, return the researcherβs h-index
.
Definition of h-index:
The h-index
is the maximum value of h such that the researcher has published at least h
papers with h
or more citations, and the remaining papers have h or fewer citations.
π‘ Examples
Example 1
Input: citations = [3,0,6,1,5]
Output: 3
Explanation: The researcher has 3 papers with at least 3 citations each.
Example 2
Input: citations = [1,3,1]
Output: 1
Explanation: Only 1 paper has at least 1 citation.
π JavaScript Solution
The optimal solution sorts the citations array and iterates through it to determine the h-index
.
Step-by-Step Implementation
var hIndex = function(citations) {
citations.sort((a, b) => b - a);
let h = 0;
for (let i = 0; i < citations.length; i++) {
if (citations[i] >= i + 1) {
h = i + 1;
} else {
break;
}
}
return h;
};
π How It Works
- Sort the citations:
- By sorting in descending order, the most cited papers come first.
- Iterate and count:
- Compare the paperβs citation count with its rank
i+1
.
- Compare the paperβs citation count with its rank
- If citations
[i] >= i + 1
, it means there are at leasti+1
papers withi+1
or more citations.- Update h accordingly.
- Stop when the condition breaks:
- As soon as a paper has fewer citations than its rank, stop iterating.
π Complexity Analysis
- > Time Complexity:
O(nlogn)
, due to sorting the citations array. - > Space Complexity:
O(1)
, as no additional data structures are used.
π Dry Run
Input: citations = [3,0,6,1,5]
- Sort citations:
[6,5,3,1,0]
- Iterate through the sorted array:
β¨ Pro Tips for Interviews
- Clarify constraints: Confirm whether the citations array can be empty or unsorted (it usually is).
- Edge cases:
- All papers have zero citations (
[0,0,0] β h-index = 0
). - Highly cited papers (
[100,200,300] β h-index = 3
). - Explain the logic: Highlight how sorting simplifies the comparison process.
- All papers have zero citations (
π Learn More
Check out the full explanation and code walkthrough on my Dev.to post:
π Jump Game II - JavaScript Solution
How do you approach problems like these? Let me know your thoughts and optimizations! π
Top comments (1)
Follow Me on GitHub π
If you found this solution helpful, check out more of my projects and solutions on my GitHub profile.
Don't forget to follow for more updates!