Skip to main content
Medium Binary Search Medium frequency

Find Peak Element

Open on LeetCode

Approach Summary

If arr[mid] < arr[mid+1], a peak exists to the right. Otherwise, it exists to the left or mid is a peak.

Full Solution & Approach

A peak is an element strictly greater than both neighbors, and the problem guarantees at least one exists. The insight is that if nums[mid] < nums[mid + 1], the array is strictly rising at mid, so a peak must exist somewhere to the right — you can discard the entire left half and still not miss one. If nums[mid] > nums[mid + 1], the array is falling at mid, so a peak exists at or to the left of mid. Each comparison eliminates half the range, giving O(log n). The proof relies on the boundaries: beyond the ends the values are treated as negative infinity, so any monotonic run must terminate in a peak. This is a different flavor of binary search — instead of finding a target value, you find a local extremum by tracking the slope direction.

Each step halves the search range — O(log n) time. Constant space — O(1).

Solution Code

Solution

def find_peak_element(nums: list[int]) -> int:
    left, right = 0, len(nums) - 1
    while left < right:
        mid = (left + right) // 2
        if nums[mid] < nums[mid + 1]:
            left = mid + 1
        else:
            right = mid
    return left

Edge Cases to Watch

  • Monotonically increasing array — the peak is the last element
  • Monotonically decreasing array — the peak is the first element
  • Single element — it is a peak by definition
  • Multiple peaks — any valid one is accepted

How to Recognize This Pattern

  • Find any peak element in O(log n)

Complexity Analysis

Time Complexity

O(log n)

Space Complexity

O(1)

Tags

Array Binary Search

This site is free. If these guides are helping your prep, consider buying me a coffee. ☕

Support →
Buy me a coffee