one v impt condition is that the edges are negative infinity. So if u have like 1,2,1,3,5,6,7. Value 7 is still valid for binar ysearch condition.
So I almost got the condition right dam. I thought
if nums[mid-1]<nums[mid]<nums[mid+1]:
But we get wrong error and index out of range. We just have to check if we are on ascending or descending slope (cur idx and cur idx +1).
Now wont there be an index out of range error?
When we are comparing nums[mid] with nums[mid + 1], we are checking the right side of the current mid. This check is safe because we only do it when mid < len(nums) - 1.
If mid is at the last index (mid = len(nums) - 1), we will not compare nums[mid] with nums[mid + 1] because the condition mid < len(nums) - 1 will not be true.
Like logically, left and right take up 2 indexes so at the extreme end, mid is at len()-2 and right is at len()-1.
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
left,right=0,len(nums)-1
while left<right:
mid = left +(right-left)//2
if nums[mid]<nums[mid+1]:
left=mid+1
else:
right=mid
return left
log n time
1 space