imashutosh51

Find peak element

Oct 16th, 2022 (edited)
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.15 KB | None | 0 0
  1. '''
  2. One observation:arr[i] can't be same as arr[i-1] && arr[i+1] for all possible i.see constraints.
  3. Why binary search working?
  4. One thing for sure,If an array doesn't contain a peek then it must be strictly increasing or decreasing
  5. that is not possible here because nums[-1] and nums[n] is INT_MIN so there is definitely a peek there.
  6.  
  7. case 1: If arr[mid-1]<arr[mid] && arr[mid+1]<arr[mid] then return mid;
  8. case 2: If arr[mid-1]>arr[mid] then arr[-1] is also smaller than arr[mid-1] then there must be some peek
  9.        in arr[-1] to arr[m1]
  10. case 3: vice versa
  11. so go in the direction of side which is having greater element than arr[mid]
  12. '''
  13.  
  14. class Solution:
  15.     def findPeakElement(self, arr: List[int]) -> int:
  16.         l,r=0,len(arr)-1
  17.         while l<=r:
  18.             mid=(l+r)//2
  19.             print(l,r,mid)
  20.             if (mid-1<0 or arr[mid]>arr[mid-1]) and (mid+1>=len(arr) or arr[mid]>arr[mid+1]):
  21.                 return mid
  22.             elif (mid-1>=0 and arr[mid-1]>arr[mid]): ###no Corner case handling here, must move in the larger neighordirection
  23.                 r=mid-1
  24.             else:
  25.                 l=mid+1
  26.         return l
  27.        
Advertisement
Add Comment
Please, Sign In to add comment