Find Peak Element

Free with account Updated Nov 19, 2026 · 4 min read
On this page

    Problem statement

    Given an array where no two neighbours are equal, return the index of any peak: an element strictly greater than its neighbours. Positions outside the array count as −∞, so the first and last elements can be peaks. Your algorithm must run in O(log n) time.

    It surprises many people that binary search works on an unsorted array. The key is that you don't need sorted data, only a rule that tells you which half definitely contains an answer. Original problem: LeetCode 162.

    Example

    In 1,2,1,3,5,6,4 both index 1 (value 2) and index 5 (value 6) are peaks; either answer is correct.
    In 1,2,1,3,5,6,4 both index 1 (value 2) and index 5 (value 6) are peaks; either answer is correct.
    Input:  [1, 2, 1, 3, 5, 6, 4]
    Output: 1 or 5
    Input:  [1, 2, 3]
    Output: 2          # the last element is a peak: its right neighbour is −∞

    Constraints (assumed)

    • 1 ≤ n ≤ 1,000 (the method works for any n).
    • nums[i] != nums[i + 1] for all valid i.

    What this question tests

    • Using binary search on a condition, not on sorted values.
    • Arguing why the half you keep must contain a peak.
    • Writing a loop that always terminates and never reads out of bounds.

    Questions to ask first

    1. Any peak, or the highest? (Here: any. The highest needs O(n).)
    2. Can neighbours be equal? (Here: no. With plateaus the halving argument breaks.)
    3. What happens at the edges? (Outside counts as −∞, so edges can be peaks.)
    4. Is O(n) acceptable? (No; O(log n) is required.)