What is Peak Element
A peak is a value greater than or equal to its neighbors. An endpoint has only one neighbor. Return any peak index. The tests use an array with a single peak, so every correct search returns the same index.
1 3 20 4 1 2
Approach
A peak is an index whose value is greater than its neighbors. On a line of bars, if the middle bar is shorter than the next one, the slope is still rising, so a peak lies to the right.
The window shrinks until lo and hi meet. That index is a peak. The picture climbs one unimodal hill so the chosen index is the unique top.
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(log n) | The window halves until one index remains. |
| Memory | O(1) | Only the two ends are stored. |
Implementation
def peak(a):
lo, hi = 0, len(a) - 1
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < a[mid + 1]:
lo = mid + 1
else:
hi = mid
return lo