From ea88e9f3888366ddb249770732b27d873aa609a9 Mon Sep 17 00:00:00 2001 From: Codebuff Contributor Date: Sat, 16 May 2026 06:06:52 +0600 Subject: [PATCH] fix(binary_search): return first occurrence when duplicates exist --- searches/binary_search.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/searches/binary_search.py b/searches/binary_search.py index bec87b3c5aec..6907eda477b8 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -196,22 +196,28 @@ def binary_search(sorted_collection: list[int], item: int) -> int: 1 >>> binary_search([0, 5, 7, 10, 15], 6) -1 + >>> binary_search([1, 2, 2, 2, 3], 2) + 1 + >>> binary_search([1, 1, 1, 2, 3], 1) + 0 """ if any(a > b for a, b in pairwise(sorted_collection)): 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: