Skip to content

Commit 93fc23b

Browse files
author
rahini
committed
Fix binary search to handle duplicates correctly
1 parent cc55b1f commit 93fc23b

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

searches/binary_search_with_duplicates.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,21 @@
1-
def binary_search_first_occurrence(arr, target):
1+
def binary_search_first_occurrence(arr: list[int], target: int) -> int:
2+
"""
3+
Return the index of the first occurrence of target in a sorted list.
4+
5+
>>> binary_search_first_occurrence([1, 2, 4, 4, 4, 5], 4)
6+
2
7+
>>> binary_search_first_occurrence([1, 2, 3], 5)
8+
-1
9+
"""
210
left, right = 0, len(arr) - 1
311
result = -1
412
while left <= right:
513
mid = (left + right) // 2
614
if arr[mid] == target:
715
result = mid
8-
right = mid - 1 # keep searching left
16+
right = mid - 1
917
elif arr[mid] < target:
1018
left = mid + 1
1119
else:
1220
right = mid - 1
1321
return result
14-
15-
if __name__ == "__main__":
16-
arr = [1, 2, 4, 4, 4, 5, 6]
17-
target = 4
18-
print(binary_search_first_occurrence(arr, target)) # Expected output: 2

0 commit comments

Comments
 (0)