Skip to content

Commit 8b710ef

Browse files
authored
Fix: Return first index for binary search with duplicate elements (#13840)
Refactored binary_search function to use bisect_left for improved efficiency.
1 parent a051ab5 commit 8b710ef

File tree

1 file changed

+6
-14
lines changed

1 file changed

+6
-14
lines changed

searches/binary_search.py

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -198,20 +198,12 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
198198
>>> binary_search([0, 5, 7, 10, 15], 6)
199199
-1
200200
"""
201-
if list(sorted_collection) != sorted(sorted_collection):
202-
raise ValueError("sorted_collection must be sorted in ascending order")
203-
left = 0
204-
right = len(sorted_collection) - 1
205-
206-
while left <= right:
207-
midpoint = left + (right - left) // 2
208-
current_item = sorted_collection[midpoint]
209-
if current_item == item:
210-
return midpoint
211-
elif item < current_item:
212-
right = midpoint - 1
213-
else:
214-
left = midpoint + 1
201+
# Use bisect_left to find the leftmost position
202+
index = bisect_left(sorted_collection, item)
203+
204+
# Check if the item exists at that position
205+
if index != len(sorted_collection) and sorted_collection[index] == item:
206+
return index
215207
return -1
216208

217209

0 commit comments

Comments
 (0)