Ternary Search & Unimodal Optimization

Find Peak Element

Medium
Solve it on LeetCode ↗

The problem

A peak is strictly greater than its neighbors (edges compare against −∞). Return the index of ANY peak in O(log n).

Stuck? Reveal hints one at a time

How to approach it

  1. 1lo = 0, hi = n − 1.
  2. 2While lo < hi: mid = (lo + hi) >> 1.
  3. 3nums[mid] < nums[mid + 1] → a peak exists strictly right: lo = mid + 1.
  4. 4Else a peak exists at mid or left: hi = mid.
  5. 5lo === hi is a peak.

Key insight

Walking uphill must end at a peak (the edge acts as −∞) — the slope at mid is a valid "which half?" oracle even though the array is unsorted.

The solution

Watch out for

  • mid + 1 is always in range because the loop keeps lo < hi.
  • Strict inequality between neighbors is guaranteed by the problem — equal plateaus would break this argument.