Find Minimum in Sorted Array
- 1 min read
- Array
- LC-Medium
- NeetCode150
- Binary Search
NeetCode Solution
- The first
if condition checks if the l and r pointers are in the sorted portion of the array. If we are, we can immediately return the leftmost element because it will be the minimum. - Else, there are two possible cases. 1) We are in the right-sorted portion of the array (the condition
nums[mid] >= nums[l]). This means that we need to go to the right-sorted portion of the array, so we updated l to mid + 1 - The other condition is if we're in the left sorted portion of the array, in which case, i
def findMin(self, nums: List[int]) -> int:
ans = nums[0]
l, r = 0, len(nums) - 1
while l <= r:
if nums[l] < nums[r]:
return min(ans, nums[l])
mid = (r + l) // 2
ans = min(ans, nums[mid])
if nums[mid] >= nums[l]:
l = mid + 1
else:
r = mid - 1
return ans