Skip to content

Commit de9d3b2

Browse files
fix: binary_search returns first index for duplicates
Fixes #13840 When duplicates exist in the sorted collection, the binary_search function now returns the index of the first occurrence instead of an arbitrary one.
1 parent 3c88735 commit de9d3b2

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

searches/binary_search.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,8 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
186186
187187
:param sorted_collection: some ascending sorted collection with comparable items
188188
:param item: item value to search
189-
:return: index of the found item or -1 if the item is not found
189+
:return: index of the found item or -1 if the item is not found.
190+
If duplicates exist, returns the index of the first occurrence.
190191
191192
Examples:
192193
>>> binary_search([0, 5, 7, 10, 15], 0)
@@ -197,22 +198,28 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
197198
1
198199
>>> binary_search([0, 5, 7, 10, 15], 6)
199200
-1
201+
>>> binary_search([1, 2, 2, 2, 3], 2)
202+
1
203+
>>> binary_search([2, 2, 2, 2, 2], 2)
204+
0
200205
"""
201206
if list(sorted_collection) != sorted(sorted_collection):
202207
raise ValueError("sorted_collection must be sorted in ascending order")
203208
left = 0
204209
right = len(sorted_collection) - 1
210+
result = -1
205211

206212
while left <= right:
207213
midpoint = left + (right - left) // 2
208214
current_item = sorted_collection[midpoint]
209215
if current_item == item:
210-
return midpoint
216+
result = midpoint
217+
right = midpoint - 1 # Continue searching left for first occurrence
211218
elif item < current_item:
212219
right = midpoint - 1
213220
else:
214221
left = midpoint + 1
215-
return -1
222+
return result
216223

217224

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

0 commit comments

Comments
 (0)