From 64108ba42296fc9f13c5b1382299a992d39e374d Mon Sep 17 00:00:00 2001 From: pro100ton Date: Wed, 19 Feb 2025 23:32:54 +0300 Subject: [PATCH] Add solution for neetcode: binary search --- neetcode/arrays/binary_search/README.md | 21 ++++++++++++++++++++ neetcode/arrays/binary_search/solution.py | 24 +++++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 neetcode/arrays/binary_search/README.md create mode 100644 neetcode/arrays/binary_search/solution.py diff --git a/neetcode/arrays/binary_search/README.md b/neetcode/arrays/binary_search/README.md new file mode 100644 index 0000000..15468a1 --- /dev/null +++ b/neetcode/arrays/binary_search/README.md @@ -0,0 +1,21 @@ +Binary Search +You are given an array of distinct integers nums, sorted in ascending order, and an integer target. + +Implement a function to search for target within nums. If it exists, then return its index, otherwise, return -1. + +Your solution must run in O(logn) time. + +Example 1: + +Input: nums = [-1,0,2,4,6,8], target = 4 + +Output: 3 +Example 2: + +Input: nums = [-1,0,2,4,6,8], target = 3 + +Output: -1 +Constraints: + +1 <= nums.length <= 10000. +-10000 < nums[i], target < 10000 diff --git a/neetcode/arrays/binary_search/solution.py b/neetcode/arrays/binary_search/solution.py new file mode 100644 index 0000000..0c19dbd --- /dev/null +++ b/neetcode/arrays/binary_search/solution.py @@ -0,0 +1,24 @@ +from typing import List + + +class Solution: + def search(self, nums: List[int], target: int) -> int: + left = 0 + right = len(nums) - 1 + while left <= right: + mid = (right + left) // 2 + if target < nums[mid]: + right = mid - 1 + elif target > nums[mid]: + left = mid + 1 + else: + return mid + return -1 + + +s = Solution() +# nums = [-1, 0, 2, 4, 6, 8] +# print(s.search(nums, 4)) +# print(s.search(nums, 3)) +nums = [-1, 0, 3, 5, 9, 12] +print(s.search(nums, 9))