PracticeNeetCode ↗LeetCode ↗
Given a sorted array of unique integers nums and an integer target, return the index of target if it exists in the array, otherwise return -1. The solution must run in O(log n) time.
left + (right - left) // 2 to avoid overflow habits carried over from other languages.left = 0, right = len(nums) - 1.mid partway between them.nums[mid] equals the target, return mid.nums[mid] is smaller than the target, search the right half; otherwise search the left half.Time: O(log n) — Space: O(1)
def search(nums: list[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1How the solution above works, piece by piece.
left and right bound the part of the array where the target can still be.mid = left + (right - left) // 2 is the middle. Written this way it can't overflow in fixed-size integer languages.left = mid + 1. Larger → right = mid - 1. mid itself is excluded both times since it was just checked.while left <= right keeps going while at least one candidate remains; if the range empties, return −1.Running it on nums = [-1, 0, 3, 5, 9, 12], target = 9: