The problem. A peak is an element strictly greater than its neighbours. Given an array nums where no two neighbours are equal, return the index of any peak. Treat the positions just outside the array as -∞, so the first or last element can be a peak too. Your solution must run in O(log n) time.
Input: nums = [1, 2, 3, 1]
Output: 2 nums[2] = 3 is bigger than 2 and 1
Input: nums = [1, 2, 1, 3, 5, 6, 4]
Output: 1 or 5 both 2 and 6 are peaks; either index is acceptedPicture the array as a mountain range: each value is a height. A peak is any point higher than the points on both sides. Because the edges count as -∞, a peak always exists — even a steadily rising array ends in one (its last element).
The problem asks for any peak, not the highest one. That freedom is what makes an O(log n) solution possible.
Free account
Sign up to read the rest of this lesson: 5 more sections, 2 drawings, a dry-run simulator and code in JavaScript, Python, Java and C++.
Still to come