↓Skip to main content
  1. LeetCode/

LeetCode 275: H-Index II

·2 mins· ·
LeetCode Medium Array Binary-Search
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-11-27

  • Submissions: Wrong Answer ×2 → Accepted ×2

Approach
#

The h-index is the largest h with h papers cited at least h times. The array is ascending; from index i to the end there are n - i papers, so the condition is citations[i] >= n - i (Binary Search Template 1). It goes false-then-true from left to right, so find the first true i; the answer is n - i, or 0 when i = n.

My Attempts
#

The first two versions scanned linearly but compared against the total count and returned nothing when no index matched: [0] returned None instead of 0.

Solution
#

class Solution:
    def hIndex(self, citations: List[int]) -> int:
        n = len(citations)
        l, r = 0, n
        while l < r:
            mid = (l + r) // 2
            if citations[mid] >= n - mid:
                r = mid
            else:
                l = mid + 1
        return n - l

Complexity
#

Time O(log n), space O(1).

Mistakes to Avoid
#

  • With all citations 0 the answer is 0; every path must return.

Interview Explanation
#

With sorted citations, from some index on there are enough citations, so I binary search the first i with citations[i] >= n - i and return n - i. Time O(log n).

Related

LeetCode 540: Single Element in a Sorted Array
·2 mins
LeetCode Medium Array Binary-Search
LeetCode 540 note: before the single element every pair starts at an even index, so binary search whether nums[mid] equals nums[mid + 1] at an even mid
LeetCode 611: Valid Triangle Number
·2 mins
LeetCode Medium Array Two-Pointers Binary-Search Greedy
LeetCode 611 note: sort, fix the longest side k, and use two pointers for the shorter sides; when the sum is large enough every i in between works, adding j - i at once
LeetCode 240: Search a 2D Matrix II
·2 mins
LeetCode Medium Array Binary-Search Divide-and-Conquer Matrix
LeetCode 240 note: start at the top-right corner, moving left when larger and down when smaller, eliminating a row or column each step
LeetCode 162: Find Peak Element
·2 mins
LeetCode Medium Array Binary-Search
LeetCode 162 note: nums[mid] < nums[mid + 1] guarantees a peak to the right (rising until the edge at worst), otherwise one at or left of mid
LeetCode 287: Find the Duplicate Number
·2 mins
LeetCode Medium Array Two-Pointers Binary-Search Bit-Manipulation
LeetCode 287 note: treat i -> nums[i] as a linked list; the duplicate is the cycle entry, found with Floyd’s algorithm in O(1) space without modifying the array
LeetCode 153: Find Minimum in Rotated Sorted Array
·2 mins
LeetCode Medium Array Binary-Search
LeetCode 153 note: compare mid with the right end: nums[mid] > nums[r] puts the minimum to the right, otherwise mid may be it, so r = mid