JJobsMoi
Meta

Find Peak Element

Codingmedium

Problem

You are given an integer array nums. An index i is considered a peak if the value at that index is strictly greater than each of its immediate neighbors. For the elements at the two ends of the array, the missing neighbor on the outside is treated as negative infinity, so the first or last element only needs to beat the one neighbor it actually has.

Your task is to return the index of any one peak in nums. If multiple peaks exist, returning any valid one is accepted.

Important rules:

  • No two adjacent elements are ever equal, so ties between neighbors never occur — a strict peak is always well defined.
  • The array is guaranteed to contain at least one peak.
  • You must not simply scan every element with a linear pass and call it done — an algorithm that examines only a logarithmic number of positions relative to the array size is expected.

Examples

Example 1:

Input: nums = [1, 3, 20, 4, 1]

Output: 2

Explanation:

  • Index 2 holds the value 20, which is greater than both its neighbors 3 and 4, so it is a peak.

Example 2:

Input: nums = [5, 4, 3, 2, 1]

Output: 0

Explanation:

  • The array is strictly decreasing, so the first element 5 has no left neighbor and is greater than the element to its right, making index 0 the only peak.

Example 3:

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

Output: 1 or 5

Explanation:

  • Index 1 (value 2) is a peak because 1 < 2 > 1.
  • Index 5 (value 6) is also a peak because 5 < 6 > 4.
  • Either index is a correct answer since the problem only asks for one valid peak.

Constraints

  • 1 <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1
  • nums[i] != nums[i + 1] for every valid index i
  • At least one peak index is guaranteed to exist in nums

Solution

Loading editor…

Sign in to get AI feedback on your answer. Your work is saved while you do.

Sign in to evaluate