Find Peak Element
Medium
Topics
A peak is an element that is strictly greater than both of its neighbours. Given a 0-indexed array nums, return the index of a peak.
Treat the elements just outside the array as -∞, so the first element is a peak if it is greater than the second, and the last is a peak if it is greater than the one before it.
Several peaks may exist. Return the smallest such index, so the answer is unambiguous.
Example 1
-∞ — which is why the first and last positions can qualify. This array has 1 peak; the answer is the smallest such index, 2.Input: nums = [1,2,3,1] Output: 2 Explanation: nums[2] = 3 is greater than both neighbours.
Example 2
Input: nums = [1,2,1,3,5,6,4] Output: 1 Explanation: Index 1 and index 5 are both peaks; the smaller index is returned.
Example 3
Input: nums = [1] Output: 0 Explanation: A single element has no neighbours, so it is a peak.
Constraints
- 1 <= nums.length <= 1000
- -2^31 < nums[i] < 2^31 - 1
- nums[i] != nums[i + 1] for every valid i
Editorial — intuition, approach, complexity and pitfalls
Intuition
Neighbouring values are never equal, so from any position one side must go up. Walking uphill can only end at a peak — the array cannot rise for ever, because the element past each end counts as -∞.
That means a peak is guaranteed to exist, and more usefully, it means half the array can be discarded at a time: if the midpoint is lower than its right neighbour then the right half must contain a peak, and symmetrically for the left.
Approach
- Keep a range
[lo, hi]that is guaranteed to contain a peak, starting with the whole array. - Take
mid. Ifnums[mid] < nums[mid + 1]the slope is rising, so a peak lies strictly right: setlo = mid + 1. - Otherwise the slope is falling (or
midis the last index), somiditself could be the peak: sethi = mid. - When
lo == hithat index is a peak. Because the range only ever shrinks towards the left on a tie-free falling slope, this converges on the leftmost peak, which is what the statement asks for.
Walkthrough
nums = [1, 2, 1, 3, 5, 6, 4]
lo=0 hi=6 mid=3 nums[3]=3 < nums[4]=5 rising -> lo=4
lo=4 hi=6 mid=5 nums[5]=6 > nums[6]=4 falling -> hi=5
lo=4 hi=5 mid=4 nums[4]=5 < nums[5]=6 rising -> lo=5
lo=hi=5 -> index 5 is a peak
(Index 1 is also a peak and is smaller, so the
leftmost-peak rule in this statement returns 1.)Complexity
- Time — O(n): the leftmost peak is found by scanning until the first element that beats both neighbours. Returning any peak instead allows the halving above, which is logarithmic.
- Space — O(1): a couple of indices.
Common Pitfalls
- Treating out-of-range neighbours as 0 rather than
-∞breaks arrays of negative values. - The halving finds a peak, not necessarily the leftmost one — this statement asks for the smallest index, so read the requirement before reaching for binary search.
Full Solution — all languages
class Solution:
def findPeakElement(self, nums):
for i in range(len(nums)):
left_ok = i == 0 or nums[i - 1] < nums[i]
right_ok = i == len(nums) - 1 or nums[i + 1] < nums[i]
if left_ok and right_ok:
return i
return -1import java.util.*;
class Solution {
public int findPeakElement(int[] nums) {
for (int i = 0; i < nums.length; i++) {
boolean leftOk = i == 0 || nums[i - 1] < nums[i];
boolean rightOk = i == nums.length - 1 || nums[i + 1] < nums[i];
if (leftOk && rightOk) return i;
}
return -1;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int findPeakElement(vector<int>& nums) {
int n = nums.size();
for (int i = 0; i < n; i++) {
bool leftOk = i == 0 || nums[i - 1] < nums[i];
bool rightOk = i == n - 1 || nums[i + 1] < nums[i];
if (leftOk && rightOk) return i;
}
return -1;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var findPeakElement = function(nums) {
for (let i = 0; i < nums.length; i++) {
const leftOk = i === 0 || nums[i - 1] < nums[i];
const rightOk = i === nums.length - 1 || nums[i + 1] < nums[i];
if (leftOk && rightOk) return i;
}
return -1;
};