1 of 5
Write a function binary_search(nums, target) that searches for target in a sorted list nums.
Return the index of target if found, or -1 if it is not in the list.
print(binary_search([1, 3, 5, 7, 9], 5)) # 2 print(binary_search([1, 3, 5, 7, 9], 7)) # 3 print(binary_search([1, 3, 5, 7, 9], 4)) # -1 print(binary_search([], 1)) # -1
| Complexity | |
|---|---|
| Time | O(log n) — halve the search space each step |
| Space | O(1) — only two pointers |
Keep two pointers, lo and hi, that mark the current search window:
lo = 0, hi = len(nums) - 1lo <= hi:
mid = (lo + hi) // 2nums[mid] == target → found, return midnums[mid] < target → target is in the right half, set lo = mid + 1nums[mid] > target → target is in the left half, set hi = mid - 1-1def binary_search(nums, target): pass print(binary_search([1, 3, 5, 7, 9], 5)) # 2 print(binary_search([1, 3, 5, 7, 9], 7)) # 3 print(binary_search([1, 3, 5, 7, 9], 4)) # -1 print(binary_search([], 1)) # -1