Visualize

Pattern visualizer

Find Peak Element

Comparing mid to its right neighbor reveals which direction is 'uphill': if the array is rising, a peak MUST exist somewhere further right (the sequence can't rise forever, and even a final rise to the array's edge counts as a peak). If it's falling, a peak must exist at mid or to its left. Either way, half the array can be safely discarded every step — no need to scan for the true global maximum, just any local peak. Animated on: nums = [1,2,3,1] — return the index of any peak element (strictly greater than both neighbors)..

Walk uphill: binary search on slope direction

time O(log n)space O(1)step 1 / 6
1
[0]
2
[1]
3
[2]
1
[3]
line 2

A peak is any element strictly greater than both neighbors (edges compare against -infinity). Binary search works because you can always walk UPHILL toward a peak — you never need to check every element.

Pseudocode
1FUNCTION findPeakElement(nums):
2 low = 0, high = the length of nums - 1
3 WHILE low < high:
4 mid = (low + high) / 2, rounded down
5 IF nums[mid] < nums[mid+1]:
6 low = mid + 1 (rising, peak is to the right)
7 ELSE:
8 high = mid (falling, peak is here or to the left)
9 RETURN low

← / → step · space play · Home restart

Where to practice Binary Search