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.
- 1 <= nums.length <= 1000
- -2^31 <= nums[i] <= 2^31 - 1
- nums[i] != nums[i+1] for all valid i
nums = [1,2,3,1]2nums = [1,2,1,3,5,6,4]5Finding a peak element is interesting because the array is unsorted. Usually, unsorted data requires a linear scan.
You can just walk the array from index 0 (O(N)). If you ever see a number that is smaller than the one you just passed, you've found a peak. This works perfectly fine but takes linear time.
Discover: We can find a peak in O(log N) time by treating the array like a mountain range and becoming a "Hill Climber."
By always following the upward slope, you are mathematically guaranteed to land on a peak.
left = 0
right = length - 1
WHILE left < right:
mid = left + (right - left) / 2
// Check the slope to the right
IF nums[mid] < nums[mid + 1]:
// Uphill slope! Peak is to the right
left = mid + 1
ELSE:
// Downhill slope! Peak is at or to the left
right = mid
RETURN leftFind Peak Element is the best example of how Binary Search can work on Unsorted data as long as there is a Monotone Trend. Even though the whole array isn't sorted, the "Upward Slope" property is something we can exploit to throw away half the mountain range at every step. This turns a slow climb into a logarithmic jump.
Hill Climbing Strategy
To find a peak, we just need to follow the slope upwards. If the right neighbor is higher, we climb right. Otherwise, the peak is to the left (or we are on it).