From 4b7c11c9e6137b8132aaf6bdc00c8bc27a11cc6f Mon Sep 17 00:00:00 2001 From: Pranavwagh1 Date: Thu, 26 Mar 2026 15:53:52 +0530 Subject: [PATCH 1/2] Fix binary search to return first occurrence for duplicates ### Fix: Binary Search Incorrect Output for Duplicates Previously, the binary_search function returned any matching index when duplicates were present. This change modifies the implementation to return the **first occurrence** of the target element. ### Changes made: - Introduced a `result` variable to track the first occurrence - Continued searching in the left half after finding a match - Updated final return to return `result` instead of immediate index ### Example: Input: [1, 2, 2, 2, 3], target = 2 Output (before): could be 1, 2, or 3 Output (after): 1 (first occurrence) This resolves issue: #13840 --- searches/binary_search.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/searches/binary_search.py b/searches/binary_search.py index 5125dc6bdb9a..e3ebd272952c 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -202,17 +202,18 @@ 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: From 238680ded53a8ba14e9e503457cf07a6fca795da Mon Sep 17 00:00:00 2001 From: Pranavwagh1 Date: Thu, 26 Mar 2026 16:01:23 +0530 Subject: [PATCH 2/2] Clean up spacing in binary_search.py Removed unnecessary spaces before and after the return statement and the result assignment. --- searches/binary_search.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/searches/binary_search.py b/searches/binary_search.py index 02ab6e820840..4c14619e0954 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -201,7 +201,7 @@ 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 + result = -1 while left <= right: midpoint = left + (right - left) // 2 current_item = sorted_collection[midpoint] @@ -212,7 +212,7 @@ def binary_search(sorted_collection: list[int], item: int) -> int: right = midpoint - 1 else: left = midpoint + 1 - return result + return result def binary_search_std_lib(sorted_collection: list[int], item: int) -> int: