From 89d59086a741b7344b7851f224ca800b4f731bb2 Mon Sep 17 00:00:00 2001 From: Andres Torres Date: Wed, 12 Nov 2025 11:15:06 -0500 Subject: [PATCH] fix: return the correct index when duplicates in binary_search --- searches/binary_search.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/searches/binary_search.py b/searches/binary_search.py index 2e66b672d5b4..871c36d0de5d 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -202,17 +202,19 @@ def binary_search(sorted_collection: list[int], item: int) -> int: raise ValueError("sorted_collection must be sorted in ascending order") left = 0 right = len(sorted_collection) - 1 + result = -1 while left <= right: midpoint = left + (right - left) // 2 current_item = sorted_collection[midpoint] if current_item == item: - return midpoint + result = midpoint + right = midpoint - 1 elif item < current_item: right = midpoint - 1 else: left = midpoint + 1 - return -1 + return result def binary_search_std_lib(sorted_collection: list[int], item: int) -> int: