01
Problem Statement
Suppose an array of length n with distinct values sorted in ascending order is rotated at some pivot unknown to you (e.g. [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). Return the minimum element of the array. You must write an O(log n) solution.
- The minimum is the only element that is smaller than its "previous" (the element at the "rotation point"). We can binary search: compare
nums[mid]withnums[right]to decide which half contains the minimum.
02
Key Observations
- If
nums[mid] > nums[right], the minimum must be in the right half(mid+1..right](the array drops after mid). Ifnums[mid] <= nums[right], the minimum is in the left half[left..mid](mid could be the minimum). So: ifnums[mid] > nums[right],left = mid + 1; elseright = mid. Useleft < rightso we don't skip the minimum; at the endnums[left]is the minimum. - We compare with
right(notleft) to correctly handle both sorted and rotated segments.
03
Approach
High-level: Binary search with left < right. If nums[mid] > nums[right], the minimum is to the right: left = mid + 1. Else the minimum is at mid or to the left: right = mid. Return nums[left].
Steps:
left = 0,right = nums.length - 1. Whileleft < right:mid = left + (right - left) / 2. Ifnums[mid] > nums[right],left = mid + 1; elseright = mid.- Return
nums[left].
04
Implementation
Java
public int findMin(int[] nums) {
int left = 0, right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] > nums[right]) {
left = mid + 1;
}
else {
right = mid;
}
}
return nums[left];
}05
Test Cases
Example 1
Input
nums = [3,4,5,1,2]
Expected
1Explanation
Minimum is 1.
06
Complexity Analysis
- Time: O(log n).
- Space: O(1).
07
Follow-ups
- Find the rotation index (pivot).