Mediumbinary-search
Find Peak Element
Problem (restated)
Return any peak index (strictly greater than neighbors). nums[-1]=nums[n]=-∞.
Intuition
Ascending mid → peak on the right; else peak on left/mid.
Approaches
Binary search on slope
UnverifiedTime O(log n)Space O(1)
Idea. If nums[mid] < nums[mid+1], lo=mid+1; else hi=mid.
Walkthrough. [1,2,3,1] → peak at index 2.
Trade-offs. Linear max is simpler but not O(log n).
Solution
export function findPeakElement(nums: number[]): number {
let lo = 0, hi = nums.length - 1;
while (lo < hi) {
const mid = lo + ((hi - lo) >> 1);
if (nums[mid]! < nums[mid + 1]!) lo = mid + 1; else hi = mid;
}
return lo;
}
export function findPeakElement(nums: number[]): number {
let lo = 0, hi = nums.length - 1;
while (lo < hi) {
const mid = lo + ((hi - lo) >> 1);
if (nums[mid]! < nums[mid + 1]!) lo = mid + 1; else hi = mid;
}
return lo;
}
Template connection
Binary search on a peak: always step toward the higher neighbor.
Reflection
- If
nums[mid] < nums[mid + 1], a peak is on the right. Any peak is enough. Why is the search still O(log n)? - The ends are treated as negative infinity. Does that make index 0 or
n - 1a legal peak? - Neighbors are never equal. What breaks if a neighbor can tie
nums[mid]?