Linear Scan
Intuition
The simplest approach is to iterate through the entire array and track the minimum value. While this does not leverage the sorted-and-rotated property and runs in linear time, it always finds the correct answer. In a rotated sorted array the minimum is the element where the ascending order breaks, so we can also find it by looking for the first element smaller than its predecessor.
Algorithm
- Initialize the minimum value as the first element.
- Iterate through the array from index 1 to n - 1.
- If the current element is smaller than the minimum, update the minimum.
- Alternatively, if nums[i] < nums[i - 1], the current element is the minimum and we can return immediately.
- Return the minimum value.
O(n)SpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
int findMin(vector<int>& nums) {
int minVal = nums[0];
for (int i = 1; i < nums.size(); i++) {
if (nums[i] < minVal) {
return nums[i];
}
}
return minVal;
}
};class Solution {
public int findMin(int[] nums) {
int minVal = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] < minVal) {
return nums[i];
}
}
return minVal;
}
}def findMin(nums: list[int]) -> int:
min_val = nums[0]
for i in range(1, len(nums)):
if nums[i] < min_val:
return nums[i]
return min_valfunc findMin(nums []int) int {
minVal := nums[0]
for i := 1; i < len(nums); i++ {
if nums[i] < minVal {
return nums[i]
}
}
return minVal
}