DIY: Find Peak Element

Solve the interview question "Find Peak Element" in this lesson.

Problem statement

Given an 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.

A peak element is an element that is strictly greater than its neighbors.

Constraints

You may assume the following constraints:

  • nums[-1] = nums[n] = -∞
  • 1 <= nums.length <= 1000
  • -231 <= nums[i] <= 231 - 1
  • nums[i] != nums[i + 1] for all valid i.

Input

The input will be an array of integers. The following is an example input:

// Sample Example - 1
[1, 2, 3, 4, 5]

// Sample Example - 2
[2, 3, 4, 5, 1, 6]

Output

The output will be an integer value representing the index of the peak element.

// Sample Example - 1
4

// Sample Example - 2
3 or 5

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.