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.[0,1,2,4,5,6,7]
if it was rotated 7
times.Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]]
1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]]
.
Given the sorted rotated array nums
of unique elements, return the minimum element of this array.
You must write an algorithm that runs in O(log n) time
.
For example:
Input: nums = [3,4,5,1,2]
Output: 1
Explanation: The original array was [1,2,3,4,5] rotated 3 times.
As another example:
Input: nums = [4,5,6,7,0,1,2]
Output: 0
Explanation: The original array was [0,1,2,4,5,6,7] and it was rotated 4 times.
Write a function to efficiently find the minimum element in a rotated sorted array.
The simplest approach is to iterate through the array and find the minimum element. This involves comparing each element with the current minimum and updating the minimum if a smaller element is found.
def find_min_brute_force(nums):
min_val = nums[0]
for num in nums:
if num < min_val:
min_val = num
return min_val
The time complexity of this approach is O(n), as we need to iterate through all the elements in the array once.
The space complexity is O(1) because we only use a constant amount of extra space to store the minimum value.
Since the array is sorted and rotated, we can use binary search to find the minimum element in O(log n) time.
left = 0
and right = nums.length - 1
.left < right
:
mid = left + (right - left) // 2
to prevent overflow.nums[mid] > nums[right]
, it means the minimum element is in the right half of the array. So, update left = mid + 1
.nums[mid]
or in the left half. So, update right = mid
.nums[left]
.def find_min_binary_search(nums):
left, right = 0, len(nums) - 1
while left < right:
mid = left + (right - left) // 2
if nums[mid] > nums[right]:
left = mid + 1
else:
right = mid
return nums[left]
The time complexity of this binary search approach is O(log n), where n is the number of elements in the array. This is because we are dividing the search space in half at each step.
The space complexity is O(1) as we only use a constant amount of extra space to store variables like left
, right
, and mid
.
right = mid
condition will eventually make left
point to the first element.