The machine must find any index where nums[i] > nums[i-1] and nums[i] > nums[i+1] — a local peak. A linear scan is O(n), but the array's structure guarantees a peak exists, so binary search can halve the space: look at mid, compare it with mid+1. If nums[mid] < nums[mid+1], the array is ascending at mid, and a peak must exist somewhere to the right; otherwise one exists to the left (including at mid itself). No array-wide sort or comparison with both neighbors is needed.
def find_peak_element(nums):
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] < nums[mid + 1]:
lo = mid + 1
else:
hi = mid
return loSteps: (1) binary search over indices, (2) compare mid with mid+1 to decide which half must contain a peak, (3) converge on a single index — the gradient guarantees termination.
Time is O(log n) with O(1) space — the greedy descent always finds a peak, not necessarily the highest one.
Trickiest edge cases: the implicit -∞ boundaries — nums[-1] = nums[n] = -∞, so the first or last element can be the peak (e.g. a strictly ascending array peaks at the last index); arrays of length 1 are already a peak; equal adjacent values make the comparison ambiguous, which is why the problem guarantees distinct neighbors.