Find Peak Element
You're given an integer array nums. An element is a peak if it's strictly larger than the elements immediately beside it, and for this problem the edges of the array are treated as bordered by negative infinity — so the first or last element only needs to beat its single real neighbor to count as a peak. Return the index of any one peak element; at least one is guaranteed to exist, and when there are several, any valid index is accepted. Aim for an O(log n) solution.
Sample Input and Output
Example 1 · Run Sample
nums = [1,2,3,1] 2 Example 2
nums = [1,2,1,3,5,6,4] 5 - 1 <= nums.length <= 1000
- -2^31 <= nums[i] <= 2^31 - 1
- nums[i] != nums[i+1] for all valid i
Test Cases (2)
Approach: Binary Search
Compare the middle element with its right neighbor. If nums[mid] > nums[mid + 1], a peak must exist in the left half (including mid) since values are decreasing. Otherwise, a peak exists in the right half. The boundary conditions guarantee at least one peak on each side of any descent.
function findPeakElement(nums) {
let left = 0, right = nums.length - 1;
while (left < right) {
const mid = (left + right) >> 1;
if (nums[mid] > nums[mid + 1]) right = mid;
else left = mid + 1;
}
return left;
}Time Complexity: O(log n)
Space Complexity: O(1)
Saved in this browser only. Private to you.