Find Peak Element
2 approaches, code in every language
Problem description
You are given an integer array. A position is called a peak when its value is strictly greater than the value immediately to its left and the value immediately to its right. For the purposes of this definition, imagine that the slots just outside the array on either end hold negative infinity, so the very first or very last element can also qualify as a peak.
Return the index of any single peak. The array can contain more than one peak, and returning the index of any one of them is accepted. Your solution should run in logarithmic time with respect to the length of the array.
Example 1
Input: nums = [1, 2, 3, 1]
Output: 2
The value 3 sitting at index 2 is larger than both of its neighbours (2 on the left and 1 on the right), so index 2 is a peak.
Example 2
Input: nums = [1, 2, 1, 3, 5, 6, 4]
Output: 5
Index 5 holds 6, which is greater than 5 on its left and 4 on its right. Index 1 (value 2) is also a valid peak, but returning any one of them is fine.
Constraints
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9nums[i] != nums[i + 1] for every valid index i
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Survey Line Crest is our own problem on the technique behind Find Peak Element: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free