← Back to DSA Animator
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.