Binary search · Medium
Find Minimum in Rotated Sorted Array: the idea to remember.
Find the smallest value in a rotated sorted array of distinct values.
The core insight
Compare the middle value to the rightmost value and keep the half containing the minimum.
Why it works
When nums[mid] > nums[right], the pivot is strictly to the right. Otherwise mid can itself be the minimum.
The mistake to avoid
Use right = mid, not mid minus one, when mid might be the minimum. Distinct values are assumed.
Time: O(log n)Space: O(1)
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
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];
}Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.