From 8b710eff1c06c329f662835a809833391b6772bf Mon Sep 17 00:00:00 2001 From: POLKAM ARAVIND <2400030648@kluniversity.in> Date: Mon, 24 Nov 2025 18:12:39 +0530 Subject: [PATCH 1/2] Fix: Return first index for binary search with duplicate elements (#13840) Refactored binary_search function to use bisect_left for improved efficiency. --- searches/binary_search.py | 20 ++++++-------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/searches/binary_search.py b/searches/binary_search.py index 2e66b672d5b4..b309dbee50d5 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -198,20 +198,12 @@ def binary_search(sorted_collection: list[int], item: int) -> int: >>> binary_search([0, 5, 7, 10, 15], 6) -1 """ - if list(sorted_collection) != sorted(sorted_collection): - raise ValueError("sorted_collection must be sorted in ascending order") - left = 0 - right = len(sorted_collection) - 1 - - while left <= right: - midpoint = left + (right - left) // 2 - current_item = sorted_collection[midpoint] - if current_item == item: - return midpoint - elif item < current_item: - right = midpoint - 1 - else: - left = midpoint + 1 + # Use bisect_left to find the leftmost position + index = bisect_left(sorted_collection, item) + + # Check if the item exists at that position + if index != len(sorted_collection) and sorted_collection[index] == item: + return index return -1 From 46f2e3d560e43c5342ba33304380c162ae5d005e Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Mon, 24 Nov 2025 12:45:49 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- searches/binary_search.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/searches/binary_search.py b/searches/binary_search.py index b309dbee50d5..e0ffd3e31216 100644 --- a/searches/binary_search.py +++ b/searches/binary_search.py @@ -200,7 +200,7 @@ def binary_search(sorted_collection: list[int], item: int) -> int: """ # Use bisect_left to find the leftmost position index = bisect_left(sorted_collection, item) - + # Check if the item exists at that position if index != len(sorted_collection) and sorted_collection[index] == item: return index