Solving Leetcode Interviews in Seconds with AI: H-Index II
Introduction
In this blog post, we will explore how to solve the LeetCode problem "275" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given an array of integers citations where citations[i] is the number of citations a researcher received for their ith paper and citations is sorted in ascending order, return the researcher's h-index. According to the definition of h-index on Wikipedia: The h-index is defined as the maximum value of h such that the given researcher has published at least h papers that have each been cited at least h times. You must write an algorithm that runs in logarithmic time. Example 1: Input: citations = [0,1,3,5,6] Output: 3 Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, their h-index is 3. Example 2: Input: citations = [1,2,100] Output: 2 Constraints: n == citations.length 1 <= n <= 105 0 <= citations[i] <= 1000 citations is sorted in ascending order.
Explanation
Here's the breakdown of the solution:
Binary Search: The core idea is to use binary search to efficiently find the h-index. Since the citations array is sorted, binary search allows us to narrow down the possible range of h-index values in logarithmic time.
H-Index Condition: For a given
midvalue (potential h-index), we check if there are at leastmidpapers with citations greater than or equal tomid.Optimization: If the condition is met, we try a larger
midvalue (search right). Otherwise, we try a smallermidvalue (search left).Runtime Complexity: O(log n)
- Storage Complexity: O(1)
Code
def hIndex(citations):
"""
Calculates the h-index of a researcher given a sorted array of citations.
Args:
citations: A list of integers representing the number of citations for each paper, sorted in ascending order.
Returns:
The h-index of the researcher.
"""
n = len(citations)
left, right = 0, n - 1
h = 0
while left <= right:
mid = (left + right) // 2
if citations[mid] >= n - mid:
h = n - mid
right = mid - 1
else:
left = mid + 1
return h