Find Peak Element
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 contains multiple peaks, return the index to any of the peaks.
You may imagine that nums[-1] = nums[n] = -ā. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in **O(log n)** time.
Examples
nums = [1,2,3,1]2nums = [1,2,1,3,5,6,4]5Constraints
1 <= nums.length <= 1000-2^31 <= nums[i] <= 2^31 - 1nums[i] != nums[i + 1] for all valid i
š” Hints
Hint 1
If nums[mid] < nums[mid + 1], there must be a peak to the right.
Hint 2
If nums[mid] > nums[mid + 1], there's a peak to the left (including mid).
Hint 3
This is because the edges are -ā, so a peak is guaranteed to exist on the ascending side.
Algorithm Complexity
Official asymptotic Big-O runtime and auxiliary memory analysis
Binary search: if nums[mid] < nums[mid+1], a peak must exist on the right (ascending). Otherwise, a peak must exist on the left (including mid). Converge to the peak.
Binary search follows the upward slope by comparing nums[mid] to nums[mid + 1], halving the interval each step.
Iterative binary search runs in-place using O(1) index pointers.
š Real-World Use Cases
Finding local maxima in signal data (audio waveforms, stock prices) efficiently using binary search on gradient direction.
š Dry Run
Find peak in [1,2,3,1]. Initialize left=0, right=3.