Skip to content
Decoder

Find Peak Element

Medium

Problem

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.

Example 1

Input
nums = [1, 2, 3, 1]
Output
2

Example 2

Input
nums = [1, 3, 5, 7, 6, 4, 2]
Output
3

Example 3

Input
nums = [5, 4, 3, 2, 1]
Output
0
Why
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.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.