diff --git a/leetcode/35.py b/leetcode/35.py new file mode 100644 index 0000000..ce944c1 --- /dev/null +++ b/leetcode/35.py @@ -0,0 +1,31 @@ +""" +Given a sorted array of distinct integers and a target value, +return the index if the target is found. +If not, return the index where it would be if it were inserted in order. + +You must write an algorithm with O(log n) runtime complexity. + +Constraints: + +1 <= nums.length <= 10^4 +-10^4 <= nums[i] <= 10^4 +nums contains distinct values sorted in ascending order. +-10^4 <= target <= 10^4 +""" + +from typing import List + + +class Solution: + def searchInsert(self, nums: List[int], target: int) -> int: + low = 0 + high = len(nums) - 1 + while low <= high: # Changed the condition to low <= high + mid = (high + low) // 2 + if target == nums[mid]: + return mid + elif target < nums[mid]: + high = mid - 1 + else: + low = mid + 1 + return low