← Binary Search
Problem
A sorted array with all-distinct values has been rotated an unknown number of
times (e.g. [3,4,5,1,2]). Find the minimum element, in better than linear
time.
30 MIN00:00unlocks in 30:00
Signal
"Sorted, but rotated" is still binary search — one of the two halves around any midpoint is always properly sorted, and that fact alone is enough to steer the search toward the rotation point without ever scanning linearly.
Approach
Compare nums[mid] against nums[right]. If nums[mid] > nums[right], the
minimum (the rotation point) must be somewhere to the right of mid, so move
left past it. Otherwise the right half (including mid) is already sorted
and contains the minimum, so pull right down to mid. Converge until
left == right.
Skeleton
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[right]:
left = mid + 1
else:
right = mid
return nums[left]
Solution
def find_min(nums: list[int]) -> int:
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[right]:
left = mid + 1
else:
right = mid
return nums[left]
Complexity
O(log n) time — halves the search window each step. O(1) space.
Pitfalls
- Comparing
nums[mid]tonums[left]instead ofnums[right]is the classic mistake — it doesn't reliably tell you which side is sorted whenmidequalsleft. Anchor onright. - Using
right = mid - 1after finding a sorted right half would skip past the minimum ifmiditself is the minimum — useright = mid, keeping it in the window. - If the array isn't guaranteed distinct (duplicates allowed),
nums[mid] == nums[right]becomes ambiguous and you can only shrink the window by one (right -= 1) instead of halving it — worth flagging that the follow-up degrades to O(n) worst case.
locked30:00 left