MediumArrayBinary Search

Find Peak Element

LeetCode
2 approaches, code in all languages

You are given an integer array. A position is called a peak when its value is strictly greater than the value immediately to its left and the value immediately to its right. For the purposes of this definition, imagine that the slots just outside the array on either end hold negative infinity, so the very first or very last element can also qualify as a peak.

Return the index of any single peak. The array can contain more than one peak, and returning the index of any one of them is accepted. Your solution should run in logarithmic time with respect to the length of the array.

Example 1

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

Output: 2

The value 3 sitting at index 2 is larger than both of its neighbours (2 on the left and 1 on the right), so index 2 is a peak.

Example 2

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

Output: 5

Index 5 holds 6, which is greater than 5 on its left and 4 on its right. Index 1 (value 2) is also a valid peak, but returning any one of them is fine.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • nums[i] != nums[i + 1] for every valid index i
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now