DSA AnimatorDSA animations
Find Peak Element LC #162 Medium Binary Search · Slope Direction
Problem

A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element and return its index. If the array contains multiple peaks, return the index of any of the peaks. You may imagine that nums[-1] = nums[n] = -∞. You must write an algorithm that runs in O(log n) time.

Example 1
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element at index 2 (3 > 2 and 3 > 1).
Example 2
Input: nums = [1,2,1,3,5,6,4]
Output: 5 (or 1)
Explanation: Index 1 (value 2) and index 5 (value 6) are both peaks.
Constraints: 1 ≤ nums.length ≤ 1000  |  -2³¹ ≤ nums[i] ≤ 2³¹−1  |  nums[i] ≠ nums[i+1]
Try Examples
Custom:
Bar Chart — Find the Peak
State Variables
lo
—
hi
—
mid
—
nums[mid]
—
nums[mid+1]
—
direction
—
Step Logic
Press ▶ Play or Next Step to begin the animation.
🏔
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
Init lo = 0, hi = n−1
2
While lo < hi: compute mid = lo + (hi−lo)/2
3
If nums[mid] < nums[mid+1]: slope goes UP → peak is RIGHT → lo = mid+1
4
Else: slope goes DOWN (or plateau) → peak is at mid or LEFT → hi = mid
5
Loop ends when lo == hi → that index is the peak → return lo
Time
O(log n)
Space
O(1)
Why It Works

Because the array has no equal adjacent elements and the virtual boundaries are −∞, a peak must exist. At any mid, if nums[mid] < nums[mid+1] the right side is going up — there's definitely a peak somewhere to the right (at minimum the next element is higher, and since the array must come back down, a local max exists). We safely eliminate the left half. The symmetric argument applies for the down slope.

How to solve Find Peak Element

LeetCode 162 · Medium · Binary Search · Pattern: Binary Search on Slope

Why the obvious approach is slow

Scanning for an element bigger than both neighbours is O(n). The array is not sorted, but the slope still tells us where to go.

The key idea

Compare the middle with its right neighbour. If the right neighbour is bigger, the slope goes up, so a peak must exist on the right. Otherwise, the middle or something on its left is a peak.

Remember

Walk uphill, and you must reach a peak. Binary search works on any direction you can decide locally.

Run the animation above on your own input, or watch the 1:17 video explanation of Find Peak Element with a dry run and Java code.

More Binary Search problems