Iterative, closed interval [lo, hi]
Halve the candidate interval on every comparison until it's empty or the target is found.
Maintain [lo, hi] as the set of indices that could still hold target. Probe the middle: equal → done; smaller → discard the left half including mid; larger → discard the right half including mid.
Algorithm
lo = 0,hi = n − 1.- While
lo <= hi:mid = lo + (hi − lo) // 2. - If
nums[mid] == targetreturnmid. - If
nums[mid] < target:lo = mid + 1; elsehi = mid − 1. - Return
-1.
- Time
- O(log n)
- Space
- O(1)
class Solution: def search(self, nums: list[int], target: int) -> int: lo, hi = 0, len(nums) - 1 # invariant: target ∈ nums[lo..hi] if present while lo <= hi: mid = lo + (hi - lo) // 2 if nums[mid] == target: return mid if nums[mid] < target: lo = mid + 1 # mid is too small; discard it and everything left else: hi = mid - 1 # mid is too big; discard it and everything right return -1