Paths Subjects Questions Quizzes Pricing Search
Intermediate Open Pro

Local Maxima in Array

Given an integer array nums where nums[i] != nums[i + 1] for all valid i, a peak element (local maximum) is an element that is strictly greater than its neighbors. Elements outside the array bounds are treated as negative infinity (so the first or last element only needs to beat its single neighbor to be a peak).

Return the index of any one peak element. There may be multiple peaks; returning the index of any of them is accepted. Your solution must run in O(log n) time.

Example 1

Input: nums = [1, 2, 3, 1]
Output: 2
Explanation: nums[2] = 3 is a peak since it is greater than both
nums[1] = 2 and nums[3] = 1.

Example 2

Input: nums = [1, 2, 1, 3, 5, 6, 4]
Output: 1 or 5
Explanation: nums[1] = 2 is a peak (neighbors 1 and 1), and
nums[5] = 6 is also a peak (neighbors 5 and 4). Either index is
accepted.

Constraints

  • 1 <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1

Share this question

← Back to Binary Search practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.