Find Peak Element
Master this topic with zero to advance depth.
Find Peak Element
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. If the array contains multiple peaks, return the index to any of the peaks. You may imagine that nums[-1] = nums[n] = -\\infty. You must write an algorithm that runs in time.
Examples
3 is a peak element and its index is 2.
Your function can return either index 1 where the peak element is 2, or index 5 where the peak element is 6.
Level I: Brute Force (Linear Scan)
Intuition
Since any element that is greater than its next neighbor is a potential peak (because we know the previous element was smaller, or it's the first element), we can just scan linearly.
Detailed Dry Run
nums = [1,2,3,1]
- 0: 1 < 2
- 1: 2 < 3
- 2: 3 > 1. Return 2.
Level II: Recursive Binary Search
Intuition
Divide the array and check the middle element's slope. If we are going up, a peak must exist on the right. If we are going down, a peak must exist on the left.
Detailed Dry Run
nums = [1,2,3,1]. L=0, R=3.
- mid=1. nums[1]=2 < nums[2]=3. Search [2, 3].
- mid=2. nums[2]=3 > nums[3]=1. Search [2, 2].
- L=R=2. Return 2.
Level III: Optimal (Binary Search on Slope)
Intuition
We can use binary search by looking at the slope. If nums[mid] < nums[mid+1], it means we are on a rising slope, and a peak must exist to the right. If nums[mid] > nums[mid+1], we are on a falling slope, and a peak must exist to the left (including mid).
Detailed Dry Run
| Step | L | R | Mid | nums[Mid] | nums[Mid+1] | Decision |
|---|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 3 | 5 | 3 < 5 → L = 4 |
| 2 | 4 | 6 | 5 | 6 | 4 | 6 > 4 → R = 5 |
| 3 | 4 | 5 | 4 | 5 | 6 | 5 < 6 → L = 5 |
| Exit | 5 | 5 | - | - | - | Return L = 5 |
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.