Skip to content

Commit ea88e9f

Browse files
author
Codebuff Contributor
committed
fix(binary_search): return first occurrence when duplicates exist
1 parent 791deb4 commit ea88e9f

1 file changed

Lines changed: 8 additions & 2 deletions

File tree

searches/binary_search.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,22 +196,28 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
196196
1
197197
>>> binary_search([0, 5, 7, 10, 15], 6)
198198
-1
199+
>>> binary_search([1, 2, 2, 2, 3], 2)
200+
1
201+
>>> binary_search([1, 1, 1, 2, 3], 1)
202+
0
199203
"""
200204
if any(a > b for a, b in pairwise(sorted_collection)):
201205
raise ValueError("sorted_collection must be sorted in ascending order")
202206
left = 0
203207
right = len(sorted_collection) - 1
208+
result = -1
204209

205210
while left <= right:
206211
midpoint = left + (right - left) // 2
207212
current_item = sorted_collection[midpoint]
208213
if current_item == item:
209-
return midpoint
214+
result = midpoint
215+
right = midpoint - 1
210216
elif item < current_item:
211217
right = midpoint - 1
212218
else:
213219
left = midpoint + 1
214-
return -1
220+
return result
215221

216222

217223
def binary_search_std_lib(sorted_collection: list[int], item: int) -> int:

0 commit comments

Comments
 (0)