<aside>
given a sorted + rotated array of unique elements return the min element in O(log n) time
[0,1,2,4,5,6,7] might become:
[4,5,6,7,**0**,1,2] if it was rotated 4 times → index 4 is pivot + minimum[**0**,1,2,4,5,6,7] if it was rotated 7 times → index (7%7) = 0 is pivot + minimum
</aside><aside>
nums[mid] with nums[right]:
nums[mid] > nums[right], the minimum must be in the right halfmidleft == right, and that index is the minimum left, right = 0, len(nums) - 1
# shrink [left, right] until one element remains
# when left == right we found the minimum
while left < right:
mid = (left + right) // 2
# left half is sorted
# mid falls in left half
if nums[mid] > nums[right]:
# minimum and pivot must be in right half
left = mid + 1
# nums[mid] <= nums[right]
# right half is sorted
# mid falls in right half
else:
# mid could be min so keep in range
right = mid
# left == right -> minimum value found
return nums[left]
<aside>
Time: O(log n) because each iteration cuts the search range roughly in half
Binary Search → the number of steps k required to reduce an array of size n down to a single element is the value that satisfies:
$$ n/2^k = 1 => 2^k = n => k = log_2(n) $$
Space: O(1) because it uses only a few pointers and no extra data structures
</aside>
input: nums = [4,5,6,7,0,1,2], left = 0, right = 6
while left < right:
| left, right | mid | nums[mid] > nums[right] |
|---|---|---|
| 0, 6 | 3 | 7 > 6 → True → left = 4 |
| 4, 6 | 5 | 1 > 6 → False → right = 5 |
| 4, 5 | 4 | 0 > 1 → False → right = 4 |
| 4, 4 → left == right → break |
output: nums[4] = 0