DEV Community

Cover image for LeetCode Challenge: 274. H-Index - JavaScript Solution πŸš€
Rahul Kumar Barnwal
Rahul Kumar Barnwal

Posted on

LeetCode Challenge: 274. H-Index - JavaScript Solution πŸš€

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.
Enter fullscreen mode Exit fullscreen mode

Example 2

Input: citations = [1,3,1]  
Output: 1  
Explanation: Only 1 paper has at least 1 citation.
Enter fullscreen mode Exit fullscreen mode

πŸ† 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;
};
Enter fullscreen mode Exit fullscreen mode

πŸ” How It Works

  1. Sort the citations:
    • By sorting in descending order, the most cited papers come first.
  2. Iterate and count:
    • Compare the paper’s citation count with its rank i+1.
  3. If citations [i] >= i + 1, it means there are at least i+1 papers with i+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]

  1. Sort citations: [6,5,3,1,0]
  2. Iterate through the sorted array:

H-Index
Output: 3


✨ Pro Tips for Interviews

  1. Clarify constraints: Confirm whether the citations array can be empty or unsorted (it usually is).
  2. 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.

πŸ“š 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! πŸš€

JavaScript #LeetCode #CodingInterview #ProblemSolving

Top comments (0)