From d1fefee020deb2f45e81de63718d15bcc0671ed9 Mon Sep 17 00:00:00 2001 From: Johan Sandoval Date: Wed, 22 Jul 2026 20:20:08 -0500 Subject: [PATCH] Finish problem 0704-binary-search --- problems/0704-binary-search/solution.py | 13 +++++++++++++ problems/0704-binary-search/solution_test.py | 13 +++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 problems/0704-binary-search/solution.py create mode 100644 problems/0704-binary-search/solution_test.py diff --git a/problems/0704-binary-search/solution.py b/problems/0704-binary-search/solution.py new file mode 100644 index 0000000..cf9162f --- /dev/null +++ b/problems/0704-binary-search/solution.py @@ -0,0 +1,13 @@ +class Solution: + def search(self, nums: list[int], target: int) -> int: + lo, hi = 0, len(nums) - 1 + i = (hi - lo) // 2 + while lo <= hi: + i = (lo + hi) // 2 + if nums[i] < target: + lo = i + 1 + elif nums[i] > target: + hi = i - 1 + else: + return i + return -1 diff --git a/problems/0704-binary-search/solution_test.py b/problems/0704-binary-search/solution_test.py new file mode 100644 index 0000000..3eccbca --- /dev/null +++ b/problems/0704-binary-search/solution_test.py @@ -0,0 +1,13 @@ +import pytest +from solution import Solution + + +@pytest.mark.parametrize( + "nums, target, expected", + [ + ([-1, 0, 3, 5, 9, 12], 9, 4), + ([-1, 0, 3, 5, 9, 12], -2, -1), + ], +) +def test_binary_search(nums, target, expected): + assert Solution().search(nums, target) == expected