Find Peak Element

MediumBinary Search · On Slope🧩 Binary SearchLeetCode #162 ↗Updated

Problem

A peak is an element strictly greater than both of its neighbours. Given nums where no two adjacent values are equal, return the index of any peak. Treat the positions outside the array as -∞, so the ends can be peaks too. Your algorithm must run in O(log n).
Input[1,2,3,1]Output2
Input[1,2,1,3,5,6,4]Output1 or 5
Input[3]Output0

1 ≤ n ≤ 1000  ·  -231 ≤ nums[i] ≤ 231-1  ·  nums[i] ≠ nums[i+1]  ·  Required: O(log n).

Try it yourself

Java
class Solution {
    public int findPeakElement(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The array need not be sorted — just look at the slope at mid. If nums[mid] < nums[mid+1] you are walking uphill, and since the far edge is -∞, a peak must exist to the right. Otherwise one exists at or left of mid.
PatternBinary Search

Instinct Sorted data, a rotated array, or find the min/max X that works where a yes/no test flips only once - halve the search space every step.

Memory hack Find the fence - every candidate reads NO NO NO YES YES, and binary search just walks to where the fence stands.

Open the Binary Search guide →

Approaches

Brute ForceLinear Scan for First Descent

Time O(n)Space O(1)

Scan left to right and return the first i with nums[i] > nums[i+1]. We only reach i because nums[i-1] < nums[i] (or i = 0), so it beats both neighbours. If the array never descends, the last element is the peak.

Java
public int findPeakElement(int[] nums) {
    for (int i = 0; i < nums.length - 1; i++) {
        if (nums[i] > nums[i + 1]) return i; // first drop is a peak
    }
    return nums.length - 1; // strictly increasing: last is a peak
}

Clean and correct, but O(n) fails the O(log n) requirement.

At a glance

LevelApproachTimeSpace
Brute ForceLinear Scan for First DescentO(n)O(1)
OptimalBinary Search on the SlopeO(log n)O(1)
Common pitfalls
  • Thinking binary search needs sorted input — here the slope is the ordering signal.
  • Using right = mid - 1 on a downhill step — can skip the actual peak.
  • Looping with left ≤ right — then mid + 1 may go out of bounds.
Interview tips
  • Justify correctness: climbing toward a -∞ edge must hit a peak.
  • Clarify that any peak is accepted, not the global maximum.
  • Mention the adjacent-distinct guarantee — plateaus would break the argument.
Pattern
Binary search on a monotone predicate → any condition at mid that proves which half still contains an answer.
My notes saved in this browser