v9.1.1
Menu

Find Peak Element

easyPROSearch & SortGoogle DSA

A peak element is an element that is strictly greater than its neighbors. Given an integer array nums, find a peak element and return its index.

You may assume nums[-1] = nums[n] = -infinity. If there are multiple peaks, return the index of any one.

Example

Input
1,2,3,1
Output
2
Reasoning
  • The input nums holds n=4n = 4 integers, 1,2,3,11, 2, 3, 1, at indices 00 to 33. Treat each end as bordered by −∞-\infty, so edge elements also have two neighbours to beat.
  • Writing xix_i for the value at index ii, a peak needs xi−1<xi>xi+1x_{i-1} < x_i > x_{i+1}, strict on both sides.
  • Index 00: 1<21 < 2, so the value 11 loses to its right neighbour. Index 11: 2<32 < 3, so it loses too. Index 33: 1<31 < 3, so it loses to its left neighbour.
  • Index 22: 2<3>12 < 3 > 1, so the value 33 beats both neighbours. It is the only peak here, and the output is its index 2, not the value 33.
  • Notice that a peak always exists: the values rise from 11 to 33 and then fall, and since adjacent values are never equal, the place where the rise turns into a fall must be a peak. With the −∞-\infty borders, even a strictly increasing list has one: its last element.

Constraints

  • 1 <= len(nums) <= 1000
  • -2^31 <= nums[i] <= 2^31 - 1
  • nums[i] != nums[i + 1] for all valid i

Learn this in

More from Google DSA

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.