Skip to problem
←

Find Peak Element

Medium 0 attempts

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.

Function contract

nums is a nonempty integer array; adjacent values are unequal.

Output: Return the zero-based index of any strict local peak, not its value. Any valid peak index is accepted.

Example 1

Input
nums = [1,2,3,1]
Output
2

Example 2

Input
nums = [1,2,1,3,5,6,4]
Output
5

Explanation: Index 1 (value 2) and index 5 (value 6) are both valid peaks.

Constraints
  • 1 <= nums.length <= 1000
  • -2^31 <= nums[i] <= 2^31 - 1
  • nums[i] != nums[i+1] for all valid i

Approach: Binary Search

Compare the middle element with its right neighbor. If nums[mid] > nums[mid + 1], keep the left half including mid; otherwise keep the right half. The retained interval has a rising boundary on its left and a falling boundary on its right (using negative infinity outside the original array), so it contains a peak. The whole interval need not be sorted.

javascript
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)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript