Start learning free

LESSON 379 OF 674 · BINARY SEARCH

Find Peak Element

Practice O(log n)

You get an array of integers nums. No two neighbors are equal.

Return the index of a peak. A peak is a value bigger than the values right next to it.

If there are several peaks, the index of any one of them is a correct answer.

The spots just outside the array count as lower than every value. So the first value is a peak if it is bigger than the second. The last value is a peak if it is bigger than the one before it.

 

Example 1:

Input: nums = [2,5,9,4]
Output: 2
Explanation: 9 is at index 2.
It is bigger than 5 on its left and 4 on its right.

Example 2:

Input: nums = [3,8,6,1,7,2]
Output: 1
Explanation: 8 at index 1 is a peak.
7 at index 4 is a peak too.
So returning 4 is also correct.

Example 3:

Input: nums = [10,7,3]
Output: 0
Explanation: The values only go down.
The spot before index 0 counts as lower than 10.
So 10, at index 0, is the peak.

 

Constraints:

  • 2 to 1,000,000 numbers.
  • Each number is from 1 to 231 - 1.
  • Two neighbors are never equal.

Note:

Your algorithm should run in O(log n) time and use O(1) extra space.


STEP 1 OF 15
    Ctrl + Enter to check