Divide & Conquer · Search

Peak Element Visualizer

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.

Risinga[mid] < a[mid + 1]. Move lo to mid + 1. The higher neighbor proves a peak exists on that side.
Not risingThe middle bar is at least as tall as the next one, so a peak is at mid or to the left. Set hi to mid.

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

Bars, and the half the slope is climbing
lo, hi = 0, n - 1
while lo < hi:
mid = (lo + hi) // 2
if a[mid] < a[mid + 1]: lo = mid + 1
else: hi = mid
return lo
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
TimeO(log n)The window halves until one index remains.
MemoryO(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