Search in rotated sorted array
- CH1 lo
- CH2 hi
- CH3 mid
One half around any middle is sorted, and its ends say whether the target can be there.
Step through it →Binary search keeps a range that must hold the answer and halves it with every look, so a million candidates take about 20 steps.
The list is sorted, so everything left of a too-small middle is smaller still, and everything right of a too-big one is larger. Each move drops only numbers that can't be the target.
Each input here has tripped up a version of this code. The stage runs the one that gets it right.
The target is the last candidate standing. A loop that runs while lo < hi stops before checking it.
One half around any middle is sorted, and its ends say whether the target can be there.
Step through it →Compare the middle with the right end to find which side the drop is on.
Step through it →Search the speeds, not the piles: too slow, then fast enough from the answer on.
Step through it →Each number binary-searches a sorted list of the smallest tail for each length.
Step through it →The same algorithm in plain Python. The lit line is the one the current frame came from.
def search(nums, target): lo, hi = 0, len(nums) - 1 while lo <= hi: mid = lo + (hi - lo) // 2 if nums[mid] == target: return mid if nums[mid] < target: lo = mid + 1 else: hi = mid - 1 return -1