Skip to content

Commit 4b7c11c

Browse files
authored
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
1 parent 3c88735 commit 4b7c11c

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

searches/binary_search.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -202,17 +202,18 @@ def binary_search(sorted_collection: list[int], item: int) -> int:
202202
raise ValueError("sorted_collection must be sorted in ascending order")
203203
left = 0
204204
right = len(sorted_collection) - 1
205-
205+
result = -1
206206
while left <= right:
207207
midpoint = left + (right - left) // 2
208208
current_item = sorted_collection[midpoint]
209209
if current_item == item:
210-
return midpoint
210+
result = midpoint
211+
right = midpoint - 1
211212
elif item < current_item:
212213
right = midpoint - 1
213214
else:
214215
left = midpoint + 1
215-
return -1
216+
return result
216217

217218

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

0 commit comments

Comments
 (0)