noodleProblems/
Find Peak Element
#114

Find Peak Element

AlgorithmmediumArrayBinary Search

A *peak element* is one that is strictly greater than its neighbors.

Given a 0-indexed integer array nums, find a peak element and return its index. If the array contains multiple peaks, return the index of **any** of them.

You may imagine that nums[-1] = nums[n] = -∞ — that is, an out-of-bounds neighbor is treated as smaller than everything, so the first or last element only needs to beat its single real neighbor. Adjacent elements are always different. Your algorithm must run in O(log n) time.

Example cases

  • single peak
    in nums = [1,2,3,1]
    out 2
    nums[2] = 3 is greater than both neighbors.
  • multiple peaks
    in nums = [1,2,1,3,5,6,4]
    out 5
    Indices 1 and 5 are both peaks; either is accepted.
  • single element
    in nums = [1]
    out 0
    A lone element has no real neighbors, so it is trivially a peak.

Constraints

  • 1 <= nums.length <= 1000
  • -2^31 <= nums[i] <= 2^31 - 1
  • nums[i] != nums[i + 1] for all valid i.
Saved
nums =
[1,2,3,1]