15% off all plans & roadmaps Use code
See plansFind Peak Element
- LeetCode 162
- Medium
- Binary Search Patterns
- Find Min/Max in Rotated Sorted Array
Updated
TL;DR: Find any index whose value is greater than both neighbors, in O(log n) time. Binary search works because the slope between mid and mid + 1 tells you which half must contain a peak.
Problem
A peak element is an element that is strictly greater than its neighbors.
Given a 0-indexed integer array nums, find a peak element and return its index. If the array has several peaks, return the index of any one of them.
You may treat nums[-1] and nums[n] as negative infinity. An element at either end is therefore greater than its missing neighbor.
You must write an algorithm that runs in O(log n) time.
Example 1
Input: nums = [1,2,3,1] Output: 2 Explanation: 3 is a peak element and your function should return the index number 2.
Example 2
Input: nums = [1,2,1,3,5,6,4] Output: 5 Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.
Constraints
1 <= nums.length <= 1000-2^31 <= nums[i] <= 2^31 - 1nums[i] != nums[i + 1]for all validi.
Constraints that matter
n <= 1000makes an O(n) scan fast in practice, but the statement requires O(log n), so a linear scan does not meet the stated requirement.- Values span the full 32-bit range, so do not use -1 or INT_MIN as a stand-in for negative infinity. Check the array boundaries directly instead.
- Adjacent values are never equal, so
nums[mid] < nums[mid + 1]always gives a clear answer. Equal neighbors would leave the slope undefined. - The array is not sorted. Only local slopes matter, so the solution must rely on a slope test and not on global order.
Hints
Hint 1
The problem looks like a search for the maximum, but you do not need the global maximum.
Hint 2
The naive solution checks each index against its neighbors and returns the first index greater than both.
Solution
Intuition
The problem looks like a search for the maximum, but you do not need the global maximum. You need any spot where the values stop rising. That spot is a local maximum, and the boundary rule guarantees that one exists.
Picture walking across a foggy field, checking only whether the ground rises or falls under your next step. If it rises, the highest point lies ahead, so you never walk back. The slope test at mid is that step, and the discarded half is the ground you no longer check.
This is a binary search. Look at mid and its right neighbor. If the value rises from mid to mid + 1, a peak must sit to the right, because the values cannot rise forever inside a finite array. If the value falls, a peak sits at mid or to the left.
Each probe discards about half the window, so the search needs about log2(n) probes. A binary search does not need sorted data. It needs one test that proves which half is safe to drop, and the slope test is that test.
Worked example
Input: nums = [10, 20, 15, 2, 23, 90, 67] Output: 5 Explanation: The value 90 at index 5 is greater than its left neighbor 23 and its right neighbor 67, so index 5 is a peak. Index 1 (value 20) is also a peak, so 1 would be a valid answer too. The page's solutions return 5.
Approach 1: Linear scan from the right
The naive solution checks each index against its neighbors and returns the first index greater than both. Missing neighbors count as negative infinity, so the ends are handled by boundary checks.
The slow part is that the scan can read every element before it finds a peak. A strictly decreasing array such as [5,4,3,2,1] has its only peak at index 0, so the scan reads all n values. The statement demands O(log n), so this approach is too slow for the stated bound.
This version walks from the right end. On the verified example it stops at index 5. Walking from the left would stop at index 1, which is also a valid peak.
Steps
- Set
iton - 1and walk down to 0. - At each
i, the left check passes wheniis 0 ornums[i] > nums[i - 1]. - The right check passes when
iisn - 1ornums[i] > nums[i + 1]. - Return
ias soon as both checks pass. - Return -1 after the loop as a guard. For
n >= 1a peak always exists, so the loop returns first.
Dry run
Start at i = 6, where the value is 67. Its left neighbor 90 is larger, so the left check fails.
At i = 5 the value is 90. Its left neighbor 23 is smaller, and its right neighbor 67 is smaller. Both checks pass, so the function returns 5.
The trace reads only 2 of the 7 values. The worst case reads all of them, as the decreasing array above shows.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Let n be the length of nums. The loop runs at most n times, and each pass does two comparisons and a few index checks, which is constant work. The total work is therefore at most a fixed constant times n, which gives O(n). The scan keeps only the index and two booleans, so the extra space is O(1).
PythonTested in our runner
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
n = len(nums)
# Walk from the right so the verified example returns 5
for i in range(n - 1, -1, -1):
left_ok = i == 0 or nums[i] > nums[i - 1]
right_ok = i == n - 1 or nums[i] > nums[i + 1]
if left_ok and right_ok:
return i
return -1JavaTested in our runner
class Solution {
public int findPeakElement(int[] nums) {
int n = nums.length;
// Walk from the right so the verified example returns 5
for (int i = n - 1; i >= 0; i--) {
boolean leftOk = i == 0 || nums[i] > nums[i - 1];
boolean rightOk = i == n - 1 || nums[i] > nums[i + 1];
if (leftOk && rightOk) {
return i;
}
}
return -1;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int n = nums.size();
// Walk from the right so the verified example returns 5
for (int i = n - 1; i >= 0; i--) {
bool leftOk = i == 0 || nums[i] > nums[i - 1];
bool rightOk = i == n - 1 || nums[i] > nums[i + 1];
if (leftOk && rightOk) return i;
}
return -1;
}
};JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {number}
*/
var findPeakElement = function(nums) {
const n = nums.length;
// Walk from the right so the verified example returns 5
for (let i = n - 1; i >= 0; i--) {
const leftOk = i === 0 || nums[i] > nums[i - 1];
const rightOk = i === n - 1 || nums[i] > nums[i + 1];
if (leftOk && rightOk) return i;
}
return -1;
};GoTested in our runner
func findPeakElement(nums []int) int {
n := len(nums)
// Walk from the right so the verified example returns 5
for i := n - 1; i >= 0; i-- {
leftOk := i == 0 || nums[i] > nums[i-1]
rightOk := i == n-1 || nums[i] > nums[i+1]
if leftOk && rightOk {
return i
}
}
return -1
}C#Tested in our runner
public class Solution {
public int findPeakElement(int[] nums) {
int n = nums.Length;
// Walk from the right so the verified example returns 5
for (int i = n - 1; i >= 0; i--) {
bool leftOk = i == 0 || nums[i] > nums[i - 1];
bool rightOk = i == n - 1 || nums[i] > nums[i + 1];
if (leftOk && rightOk) return i;
}
return -1;
}
}The Find Min/Max in Rotated Sorted Array infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Find Min/Max in Rotated Sorted Array
Part of Binary Search Patterns
Approach 2: Binary search on the slopeOptimalFind Min/Max in Rotated Sorted Array
What is slow in the linear scan is that it examines values that cannot change the answer. One comparison at mid can rule out half of the window. If nums[mid] < nums[mid + 1], the values rise at mid, so a peak lies in [mid + 1, right]. If nums[mid] > nums[mid + 1], the values fall at mid, so a peak lies in [left, mid].
The proof rests on an invariant. The value at left is greater than its left neighbor, or left is 0. The value at right is greater than its right neighbor, or right is n - 1. Both hold at the start, because the ends see negative infinity.
The update left = mid + 1 keeps the invariant because nums[mid + 1] > nums[mid]. The update right = mid keeps it because nums[mid] > nums[mid + 1].
With the invariant, a peak must exist in the window. Take the first index k in the window where nums[k] > nums[k + 1]. It exists because right qualifies. The index k is a peak, because every earlier index rises into it and the first step is covered by the left-end invariant.
Why it is correct. The window keeps a rising edge on its left and a falling edge on its right, so a peak must lie between them. Each update drops a half only when the slope at mid shows a peak remains in the half that is kept. When the window shrinks to one index, the invariant forces that index to be a peak.
Steps
- Set
leftto 0 andrightton - 1. - While
left < right, computemid = left + (right - left) / 2. - If
nums[mid] < nums[mid + 1], setleft = mid + 1. - Otherwise set
right = mid. - When the loop ends,
leftequalsright. Returnleft.
Dry run
The table traces the verified example [10, 20, 15, 2, 23, 90, 67].
| Step | left | right | mid | nums[mid] | nums[mid + 1] | Action |
|---|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 2 | 23 | 2 < 23, so left = 4 |
| 2 | 4 | 6 | 5 | 90 | 67 | 90 > 67, so right = 5 |
| 3 | 4 | 5 | 4 | 23 | 90 | 23 < 90, so left = 5 |
| 4 | 5 | 5 | - | - | - | left equals right, stop |
The loop ends with left = right = 5. Index 5 holds 90, which is greater than both 23 and 67, so the function returns 5.
Complexity
| Time | O(log n) |
|---|---|
| Space | O(1) |
Let n be the array length and s the current window size, which is right - left + 1. A pass keeps either the part after mid or the part up to mid, and each part has at most ceil(s / 2) elements. After k passes the window has at most ceil(n / 2^k) elements, so the loop ends after about log2(n) passes.
Each pass does constant work, so time is O(log n). The solution stores only left, right and mid, so space is O(1).
PythonTested in our runner
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
left, right = 0, len(nums) - 1
# Invariant: a peak lies in nums[left..right]
while left < right:
mid = left + (right - left) // 2
if nums[mid] < nums[mid + 1]:
# Rising at mid, so a peak lies to the right
left = mid + 1
else:
# Falling at mid, so mid or a point to its left is a peak
right = mid
return leftJavaTested in our runner
class Solution {
public int findPeakElement(int[] nums) {
int left = 0;
int right = nums.length - 1;
// Invariant: a peak lies in nums[left..right]
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < nums[mid + 1]) {
// Rising at mid, so a peak lies to the right
left = mid + 1;
} else {
// Falling at mid, so mid or a point to its left is a peak
right = mid;
}
}
return left;
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
int findPeakElement(vector<int>& nums) {
int left = 0;
int right = nums.size() - 1;
// Invariant: a peak lies in nums[left..right]
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < nums[mid + 1]) {
// Rising at mid, so a peak lies to the right
left = mid + 1;
} else {
// Falling at mid, so mid or a point to its left is a peak
right = mid;
}
}
return left;
}
};JavaScriptTested in our runner
/**
* @param {number[]} nums
* @return {number}
*/
var findPeakElement = function(nums) {
let left = 0;
let right = nums.length - 1;
// Invariant: a peak lies in nums[left..right]
while (left < right) {
const mid = left + Math.floor((right - left) / 2);
if (nums[mid] < nums[mid + 1]) {
// Rising at mid, so a peak lies to the right
left = mid + 1;
} else {
// Falling at mid, so mid or a point to its left is a peak
right = mid;
}
}
return left;
};GoTested in our runner
func findPeakElement(nums []int) int {
left, right := 0, len(nums)-1
// Invariant: a peak lies in nums[left..right]
for left < right {
mid := left + (right-left)/2
if nums[mid] < nums[mid+1] {
// Rising at mid, so a peak lies to the right
left = mid + 1
} else {
// Falling at mid, so mid or a point to its left is a peak
right = mid
}
}
return left
}C#Tested in our runner
public class Solution {
public int findPeakElement(int[] nums) {
int left = 0;
int right = nums.Length - 1;
// Invariant: a peak lies in nums[left..right]
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < nums[mid + 1]) {
// Rising at mid, so a peak lies to the right
left = mid + 1;
} else {
// Falling at mid, so mid or a point to its left is a peak
right = mid;
}
}
return left;
}
}Common mistakes
- Using
while left <= rightwithright = mid - 1. The stepright = mid - 1can skipmid, which may be the only peak. Keepwhile left < rightandright = mid, so the window always contains a peak. - Swapping the branches, so the code sets
left = mid + 1whennums[mid] > nums[mid + 1]. A falling slope means the peak is atmidor to the left. Move right only on a rising slope. - Reading
nums[mid + 1]whenmidisn - 1. This happens when the loop condition isleft <= right. Keepleft < right, which keepsmidbelowright. - Checking
nums[i] > nums[i + 1]in the linear scan ati = n - 1. That index does not exist. Treat a missing neighbor as negative infinity with an explicit boundary check. - Returning
nums[left]when the function must return an index. The value 90 is not the index 5. Returnleftfor this signature, and return the value only in the follow-up.
Edge cases
- A single element
[7]. The loop never runs, and the function returns 0. - Two elements
[1,2]return 1, and[2,1]returns 0. Each element is checked against the outside negative infinity. - A strictly increasing array
[1,2,3,4]returns 3, and a strictly decreasing array[4,3,2,1]returns 0. - Extreme values
[-2147483648,-2147483647]return 1. The comparisons work without sentinel arithmetic, so no overflow occurs. - Several peaks
[1,3,2,4,3]can return either 1 or 3. Both answers are correct, and the tests accept either.
Follow-ups interviewers ask
- What if the function must return the peak value instead of the index?
- Return
nums[left]after the loop. Bothleftandrightname the final peak, so the value comes from the same position and no extra scan is needed. - Can you sort the array to find a peak?
- Sort the indices by value in descending order. The first index is the global maximum, and it is a peak because both neighbors are strictly smaller. Sorting costs O(n log n) time and O(n) space for the index array, which misses the O(log n) bound.
- What if equal neighbors are allowed?
- A strict peak may not exist, as in
[2,2,2]. The same loop still returns an index that is greater than or equal to both neighbors. The earlier invariant still holds, so the window always contains such an index.
Find Peak Element FAQ
What is the time complexity of Find Peak Element?
The binary search version runs in O(log n) time, which the statement requires. The linear scan runs in O(n) time. Both use O(1) extra space.
Why use binary search for Find Peak Element?
The array is not sorted, but one comparison of nums[mid] and nums[mid + 1] tells you which half must contain a peak. That test lets each step discard half the window, which gives the logarithmic bound.
Can Find Peak Element be solved in O(1) extra space?
Yes. The binary search stores only left, right and mid. The linear scan stores only an index and two booleans. Neither solution needs a map, a stack or a copy of the array.
Does binary search on this problem need the array to be sorted?
No. The loop never checks global order. It relies on local slopes and on the rule that values outside the array count as negative infinity.
Why does the binary search return left and not mid?
The loop ends when left equals right, so both name the same index. Returning left matches the state after the last update and avoids an extra variable.
Asked at
See which companies ask this — Pro
Related problems
- Search in Rotated Sorted Array · same technique: Find Min/Max in Rotated Sorted Array
- Find Minimum in Rotated Sorted Array · same technique: Find Min/Max in Rotated Sorted Array
- Search in Rotated Sorted Array II · same technique: Find Min/Max in Rotated Sorted Array
- Peak Index in a Mountain Array · same technique: Find Min/Max in Rotated Sorted Array
- Find in Mountain Array · same technique: Find Min/Max in Rotated Sorted Array
- Koko Eating Bananas · same pattern: Binary Search Patterns
- Search a 2D Matrix · same pattern: Binary Search Patterns
- Find K Closest Elements · same pattern: Binary Search Patterns
- Capacity To Ship Packages Within D Days · same pattern: Binary Search Patterns
- Find First and Last Position of Element in Sorted Array · same pattern: Binary Search Patterns