Given an array that isn’t guaranteed to be a single mountain, find any element greater than both
its neighbors — edges count as -∞ neighbors, and any valid peak can be returned.
(LeetCode 162)
def findPeakElement(arr): n = len(arr)
if n == 1: return 0 if arr[0] > arr[1]: return 0 if arr[n-1] > arr[n-2]: return n-1
low, high = 1, n - 2 # exclude edges, already checked while low <= high: mid = (low + high) // 2
if arr[mid] > arr[mid-1] and arr[mid] > arr[mid+1]: return mid
if arr[mid] < arr[mid+1]: # climbing, peak is to the right low = mid + 1 else: # descending, peak is to the left high = mid - 1
return -1 # failsafe, a peak always existsTime: O(log n). Space: O(1). Think of it like walking a trail: climbing means the peak is ahead, descending means it’s behind, and at the top both sides go down.