Find Peak Element

Medium Binary Search

nums is a list of whole numbers in which no two numbers next to each other are equal.

A peak is a position whose number is larger than the numbers on either side of it. Beyond both ends of the list, count the outside as lower than every number: the first position need only beat the second, the last only the one before it, and a list of one number has its peak at position 0.

Return the position of a peak, counting from 0. Every such list has at least one, and when it has several, any of them is right.

Example 1

Input: nums = [3,8,5,1,6,2]
One right answer: 1

Position 1 holds 8, larger than the 3 and the 5 on either side of it, so it is a peak. So is position 4, which holds 6, and either answer is right.

Example 2

Input: nums = [2,5,9,14]
One right answer: 3

The numbers only rise, and the outside past the end counts as lower, so the last position is the one peak.

Example 3

Input: nums = [10,4,7,3,8]
One right answer: 2

Constraints

  • 1 ≤ nums.length ≤ 4 × 10⁵
  • -2³¹ ≤ nums[i] ≤ 2³¹ - 1
  • nums[i] ≠ nums[i + 1]: numbers next to each other differ

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

More Binary Search

All Binary Search problems