AlgoInsight

DSA problem

Find Peak Element

MediumBinary SearchPattern: Binary Searchtop150GoogleMicrosoftAmazonBloombergApple

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 one of them. You may imagine that nums[-1] = nums[n] = -∞. You must write an algorithm that runs in O(log n) time.

The O(log n) bound is the surprising part — peak finding sounds like it requires scanning everything, but it does not. The key invariant: at any window [lo, hi], if you look at mid and compare it to mid + 1, you can always discard one side. If nums[mid] < nums[mid + 1], the right side is ascending out of mid; somewhere to the right there must be a peak (eventually the sequence has to descend or hit the virtual -∞ past index n - 1). Symmetrically, if nums[mid] > nums[mid + 1], a peak exists to the left of, or at, mid.

Use the lower-bound style binary search: lo = 0, hi = n - 1, loop while lo < hi. Inside, compute mid = lo + (hi - lo) / 2, then branch on the comparison between nums[mid] and nums[mid + 1]. If the right neighbor is larger, set lo = mid + 1; otherwise hi = mid. When the loop ends, lo == hi is an index of a peak.

The reason mid + 1 cannot run off the array is that hi starts at n - 1 and only ever decreases; mid < hi whenever lo < hi, so mid + 1 <= hi <= n - 1. The whole search runs in O(log n) time and O(1) space.

Examples

Example 1
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 at index 2 is strictly greater than both neighbors (2 and 1), so 2 is a valid peak index.
Example 2
Input: nums = [1,2,1,3,5,6,4]
Output: 5 (or 1)
Explanation: Both 2 (index 1) and 6 (index 5) are peaks; the algorithm may return either depending on the bisection path.
Example 3
Input: nums = [1]
Output: 0
Explanation: A single element is trivially a peak by the virtual -∞ boundary rule.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

binary-searcharray

Browse all DSA problems