Skip to content

Find Peak Element

MediumBinary Search
Decode it first. Clues, constraints, pattern and plan before any code.

A peak is an element strictly greater than its neighbours. Imagine nums[-1] and nums[n] are negative infinity, so the ends can be peaks too. Given nums where no two neighbours are equal, return the index of a peak. If there are several you may return any, but every test here has exactly one. You must run in O(log n) time.

nums = [1, 2, 3, 1]             →  2
nums = [1, 3, 5, 7, 6, 4, 2]    →  3
nums = [5, 4, 3, 2, 1]          →  0   (the left end counts)

Constraints

  • 1 <= nums.length <= 1000
  • -2^31 <= nums[i] <= 2^31 - 1
  • nums[i] != nums[i + 1] for every valid i.