Find a peak element (binary search)
Medium TimeO(log n) SpaceO(1)
A peak is a value strictly greater than both of its neighbours, with anything off either end counting as negative infinity — so the first and last elements have one neighbour each and either can be a peak. Given nums, in which no two neighbours are ever equal, return the index of any peak. In [1, 2, 1, 3, 5, 6, 4] index 5 qualifies, and so does index 1.
Examples
Example 1
- Input
- nums = [1, 2, 1, 3, 5, 6, 4]
- Output
5nums[5]is 6, above the 5 before it and the 4 after it.
Example 2
- Input
- nums = [3, 2, 1]
- Output
0nums[0]is 3, with nothing off the left end and 2 to its right.
The Code
function findPeakElement(nums) {
let lo = 0;
let hi = nums.length - 1;
while (lo < hi) {
const mid = Math.floor((lo + hi) / 2);
if (nums[mid] < nums[mid + 1]) lo = mid + 1;
else hi = mid;
}
return lo;
}
findPeakElement([1, 2, 1, 3, 5, 6, 4]);Done
More like this
All searching examples (8) →- Binary search Halve the search range each step with lo / mid / hi.
- Linear search Scan left to right until you find the value.
- Rotated search Binary search where one half is always sorted — use it.
- Binary search (recursive) The same halving, written as a call tree instead of a loop.
- Insert position Binary search that returns where a value *would* go.
- Search on the answer Binary search the answer space, not the array.