Find Peak Element
Find any local peak strictly greater than its neighbors in an unsorted array in O(log n) time by binary searching along the uphill slope.
01The problem
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 strictly greater than a neighbor that is outside the array.
You must write an algorithm that runs in O(log n) time.
| Input | Output | Why |
|---|---|---|
nums = [1, 2, 3, 1] | 2 | 3 is strictly greater than neighbors 2 and 1 |
nums = [1, 2, 1, 3, 5, 6, 4] | 1 or 5 | Index 1 (val 2) and index 5 (val 6) are peaks |
nums = [1] | 0 | Single element has out-of-bounds neighbors -∞ |
Constraints: 1 to 1,000 numbers, no two adjacent elements are equal (nums[i] != nums[i+1]).
Loading the rest of the lesson…