Skip to content

Commit 0cb1599

Browse files
Optimize binary search logic for h-index calculation
Refined the binary search to improve clarity and efficiency in determining the h-index. Enhanced comments to explain edge cases, conditions, and the logic for narrowing down the search space. This ensures better maintainability and understanding of the algorithm.
1 parent 1f6ebea commit 0cb1599

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

Diff for: Binary Search/Tricky Invariant/h_index_II.py

+11-7
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,24 @@ def h_index(citations: List[int]) -> int:
1010
left = 0
1111
right = n - 1
1212

13+
# We need to find the rightmost 'index' such that: (citations[index] <= n - index)
1314
while left <= right:
14-
mid = (left + right) // 2
15+
mid = left + (right - left) // 2
1516

16-
# If the citation at mid, equals the number of papers with citations >= citations[mid]
17+
# There are (n - mid) papers with an equal or higher citation count than citations[mid]
18+
# If (citations[mid] == n - mid) it's the optimal result and can be returned right away
1719
if citations[mid] == n - mid:
18-
return citations[mid] # Return the h-index
20+
return n - mid
1921

20-
# If citations at mid are less than the required h-index condition
22+
# If citations[mid] are less than (n - mid), narrow down on the right half to look for a paper
23+
# at a future index that meets the h-index criteria. Otherwise, narrow down on the left half
2124
if citations[mid] < n - mid:
22-
left = mid + 1 # Shift the search to the right half
25+
left = mid + 1
2326
else:
24-
right = mid - 1 # Shift the search to the left half
27+
right = mid - 1
2528

26-
# If no exact match is found, return the best possible h-index value
29+
# We didn't find an exact match, so there are exactly (n - left) papers that have citations
30+
# greater than or equal to citations[left], and that is our answer
2731
return n - left
2832

2933

0 commit comments

Comments
 (0)