162. Find Peak Element
At a Glance
- Topic: binary-search
- Pattern: Binary Search (Slope / neighbor compare)
- Difficulty: Medium
- Companies: Google, Amazon, Meta, Apple, Bloomberg
- Frequency: High
- LeetCode: 162
Problem (one-liner)
Given an array where nums[-1] and nums[n] are treated as negative infinity, return any index that is a strict local peak (nums[index] > neighbors). Guarantee a peak exists.
Recognition Cues
- “Peak” with boundaries at negative infinity
O(log n)expected- Compare
midtomid+1to see uphill vs downhill
Diagram
At-a-glance flow (replace with problem-specific Mermaid as you refine this note). camelCase node IDs; no spaces in IDs.
Loading diagram…
Approaches
- Brute force —
O(n)— scan fornums[index] > nums[index+1]andnums[index] > nums[index-1]. - Better — not needed.
- Optimal —
O(log n)time /O(1)space — ifnums[mid] < nums[mid+1], a peak exists to the right; else to the left (inclusivemid).
Optimal Solution
Go
func findPeakElement(nums []int) int {
left, right := 0, len(nums)-1
for left < right {
mid := left + (right-left)/2
if nums[mid] < nums[mid+1] {
left = mid + 1
} else {
right = mid
}
}
return left
}JavaScript
function findPeakElement(nums) {
let left = 0;
let right = nums.length - 1;
while (left < right) {
const mid = left + Math.floor((right - left) / 2);
if (nums[mid] < nums[mid + 1]) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}Walkthrough
nums = [1,2,3,1]
| step | left | right | mid | nums[mid] vs nums[mid+1] | move |
|---|---|---|---|---|---|
| 1 | 0 | 3 | 1 | 2 < 3 | left = 2 |
| 2 | 2 | 3 | 2 | 3 > 1 | right = 2 |
Return index 2. Invariant: a peak always remains in [left, right].
Edge Cases
- Single element — peak index
0. - Strictly increasing — peak at last index.
- Strictly decreasing — peak at index
0.
Pitfalls
- Off-by-one comparing
midtomid-1only — need consistent uphill rule withmid+1. - Assuming unique peak — any peak is acceptable.
Similar Problems
- 153. Find Minimum in Rotated Sorted Array — also compares halves via endpoints.
- 704. Binary Search — baseline shrinking interval.
- 875. Koko Eating Bananas — binary search driven by a local monotone signal.
Variants
- 2D peak — compare to four neighbors; move toward larger neighbor.
- Bitonic array peak — known structure; similar slope logic.
Mind-Map Tags
#binary-search #peak #slope #neighbor-compare
Last updated on
Spotted something unclear or wrong on this page?