AAlgoLoopSpaced repetition for LeetCode
MEDIUMBinary SearchLeetCode ↗

Find Peak Element

The key idea

Out-of-bounds neighbours act as negative infinity, so a peak always exists. At any index, the side with the larger neighbour must contain a peak: keep walking uphill via binary search until lo and hi meet.

Problem

A peak element is an element that is strictly greater than its neighbours.

Given a 0-indexed integer array nums, find a peak element and return its index. If the array contains multiple peaks, return the index to any of the peaks.

You may imagine that nums[-1] = nums[n] = -∞. In other words, an element is always considered to be strictly greater than a neighbour that is outside the array.

You must write an algorithm that runs in O(log n) time.

Constraints

Examples

Input: nums = [1,2,3,1] Output: 2
Input: nums = [1,2,1,3,5,6,4] Output: 5

Complexity

Time: O(log n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Binary Search problems