Example 1
ready- Input
nums = [ 4, 5, 6, 7, 0, 1, 2 ]- Expected
0- Why
- 0 begins the low-value piece
A sorted shelf has been spun around, but its smallest book still marks the seam.
You're given a non-empty array nums that began in strictly increasing order. It was
then rotated, meaning a prefix — a block from the front — may have been moved to
the end without changing the order inside either piece. Return the smallest value.
The rotation amount is unknown. It may also be zero, leaving the original sorted order untouched.
A few ground rules:
1 <= nums.length <= 100_000-1_000_000_000 <= nums[i] <= 1_000_000_000nums is a rotation of a strictly increasing array.Hints
Compare the middle value with nums[right]. That rightmost value tells you which
sorted piece contains the middle.
If nums[middle] > nums[right], the minimum must be strictly to the right of
middle.
Otherwise, middle may itself be the minimum, so keep it with right = middle.
Stop when left == right.
If duplicate values were allowed, which comparison would become ambiguous, and how would that change the worst-case running time?
Visible cases
nums = [
4,
5,
6,
7,
0,
1,
2
]0nums = [
11,
13,
15,
17
]11nums = [
2,
1
]1Interview signal
Keep the smallest value seen while walking through the array.
def find_min(nums: list[int]) -> int:
smallest = nums[0]
for value in nums[1:]:
smallest = min(smallest, value)
return smallestTime O(n). Space O(1). Correct, but it ignores the two sorted runs created by the rotation.
Keep an interval that contains the minimum and compare its middle value with its right edge.
nums[middle] > nums[right], middle sits on the high-value piece. The seam and
minimum are strictly to its right, so set left = middle + 1.middle sits on the low-value piece. It may be the minimum, so preserve
it with right = middle.def find_min(nums: list[int]) -> int:
left, right = 0, len(nums) - 1
while left < right:
middle = left + (right - left) // 2
if nums[middle] > nums[right]:
left = middle + 1
else:
right = middle
return nums[left]When the pointers meet, every discarded position has been proved too high, and the one
remaining index is the rotation seam. The unrotated case works too: every middle value
is below the right edge, so right keeps moving toward index 0.
Time O(log n). Space O(1). Each comparison removes at least half of the remaining interval.
Ready to run.
3 cases are queued.
Visible testcase
Case 1
Expected
0