Example 1
- Input
- nums = [3,4,5,1,2]
- Output
- 1
The values rise from 3 through 5, then drop to 1 at index 3. Every other value is larger, so return the value 1, not its index 3.
Given a rotated sorted array of unique integers, return its smallest element. Comparing the middle against the right end reveals which half holds the rotation point, giving a logarithmic search.
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2] if it was rotated 4 times.
Given the sorted rotated array nums of unique elements, return the minimum element of this array. You must write an algorithm that runs in time.
n == nums.length1 <= n <= 5000-5000 <= nums[i] <= 5000nums are unique.nums is sorted and rotated between 1 and n times.The values rise from 3 through 5, then drop to 1 at index 3. Every other value is larger, so return the value 1, not its index 3.
The minimum 0 is inside the array at index 4, after the drop from 7. It remains the answer even though both endpoints are larger.
A full-length rotation preserves increasing order. There is no internal drop, so the first value 11 is the minimum.
With one element, that value is necessarily the minimum. The binary-search loop runs zero times.
Rotation cuts a strictly increasing array into two increasing pieces; when a drop exists, the first value after it is the minimum. In [3, 4, 5, 1, 2], that value is 1. Scanning finds it by checking every value. Binary search instead keeps an interval containing the minimum and compares its middle with its right endpoint to remove half the candidates.
Reveal Scan For Minimum: intuition, complexity, and code
nums[mid] > nums[right], move left to mid + 1; otherwise retain mid by moving right to mid.[11, 13, 15, 17] keeps moving the right boundary left until index 0.[2, 1] resolves in a single middle-against-right comparison.right = mid - 1 can discard the minimum itself: in [3, 1, 2], mid already holds 1.left = mid can stall on two candidates such as [2, 1]; the larger middle is safely excluded with mid + 1.left <= right and right = mid never shrinks a singleton. Stop when the boundaries meet.left gives an index, but this problem asks for nums[left], the value.In rotated sorted arrays the right end anchors the search: the middle against the right end tells you which half holds the rotation point.