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 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.
1 and n times, meaning it can also be 0 times (the array is not rotated).To solve this problem efficiently in O(log n) time, we can use a modified binary search algorithm:
left to 0 and right to len(nums) - 1.left is less than right:
mid.nums[mid] > nums[right], the smallest element is in the right half, so set left to mid + 1.right to mid.left will point to the smallest element. Return nums[left].def findMin(nums):
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[right]:
left = mid + 1
else:
right = mid
return nums[left]
O(log n) time because we are using a binary search approach, which halves the search space in each step.O(1) because we are using only a constant amount of additional space.This approach efficiently finds the minimum element in a rotated sorted array using properties of the rotation and binary search technique.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?