When a list is sorted, you never need to look at every element. Comparing against the middle tells you which half the target must be in, so each step halves the work: O(log n) instead of O(n).
A surveyor lists the altitudes of her markers in metres, smallest first, and no two markers share an altitude (negative values are below sea level). Given that list nums of distinct integers in ascending order and one altitude target, report where target sits: its index in nums, or -1 when no marker has that altitude.
Examples
Input: nums = [-4, 1, 6, 8, 13, 20], target = 13
Output: 4
Input: nums = [-4, 1, 6, 8, 13, 20], target = 2
Output: -1
Constraints
0 <= len(nums) <= 10**4- All elements of
numsare distinct and sorted ascending. - Aim for O(log n) time. Do not use
list.index()or thebisectmodule.
Goals
- Maintain lo and hi bounds that always contain the answer if it exists
- Compute the midpoint and discard half of the search space each step
- Write a loop condition and updates that cannot loop forever