Code Logo

Find Peak Element

Published at24 Jul 2026
Medium 0 views
Like0

A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array, find the index of any peak element. The array may contain multiple peaks; return the index of any one. You must write an algorithm that runs in O(log n) time.

The straightforward O(n) scan checks each element and its neighbors. But binary search works because of the array's structure: if we look at the middle element, and it is less than its right neighbor, then there must be a peak somewhere to the right. Conversely, if the middle element is less than its left neighbor, there must be a peak to the left. If the middle is greater than both neighbors, it is itself a peak.

This logic relies on the fact that the array boundaries (index -1 and index n) are considered negative infinity. So if the middle is less than its right neighbor, the right half must contain a peak — even if the right half is strictly decreasing from that point onward, the rightmost element is a peak since its right neighbor (the boundary) is negative infinity.

Edge cases include a single element (it is a peak since both neighbors are negative infinity), an array sorted ascending (the last element is a peak), and an array sorted descending (the first element is a peak).

Example Input & Output

Example 1
Input
[1,2,3,1]
Output
2
Explanation

Peak 3 at index 2 is greater than neighbors.

Example 2
Input
[1,2,1,3,5,6,4]
Output
5
Explanation

Peak 6 at index 5. Also index 1 is a valid answer.

Example 3
Input
[1]
Output
0
Explanation

Single element is always a peak.

Example 4
Input
[1,2,3,4,5]
Output
4
Explanation

Strictly ascending, last element is peak.

Example 5
Input
[5,4,3,2,1]
Output
0
Explanation

Strictly descending, first element is peak.

Algorithm Flow

Recommendation Algorithm Flow for Find Peak Element
Recommendation Algorithm Flow for Find Peak Element

Solution Approach

Binary search: if nums[mid] < nums[mid+1], peak is on the right; else peak is on the left (or mid itself).

function solution(nums) {
  var lo = 0, hi = nums.length - 1;
  while (lo < hi) {
    var mid = Math.floor((lo + hi) / 2);
    if (nums[mid] > nums[mid + 1]) hi = mid;
    else lo = mid + 1;
  }
  return lo;
}

Time O(log n), Space O(1).

Best Answers

java
class Solution {
    public int solution(int[] nums) {
        int lo = 0, hi = nums.length - 1;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] > nums[mid + 1]) hi = mid;
            else lo = mid + 1;
        }
        return lo;
    }
}