162. Find Peak Element
Intitution
A peak is an element that is greater than its immediate neighbors. Because we can assume nums[-1]
and nums[n]
are -∞
, the array is guaranteed to have at least one peak.
To find a peak in O(log n) time, we can use binary search:
If
nums[mid]
is greater than both neighbors → it's a peak.If the right neighbor is greater → the peak lies to the right.
Else → the peak lies to the left.
This works because in a unimodal-like structure, there's always a path toward a peak.
Complexity
Space Complexity
Time Complexity
Code
Last updated