Find Peak Element Medium 0 attempts
LeetCode ↗

Find Peak Element

Medium Sorting&Searching LeetCode

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.

Input Format
Implement findPeakElement(nums). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement. Any result satisfying the statement is accepted.

Sample Input and Output

Example 1 · Run Sample

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

Example 2

Input
nums = [1,2,1,3,5,6,4]
Output
5
Constraints
  • 1 <= nums.length <= 1000
  • -2^31 <= nums[i] <= 2^31 - 1
  • nums[i] != nums[i+1] for all valid i
Test Cases (2)
Case 1
Args: [[1,2,3,1]] Expected: 2
Case 2
Args: [[1,2,1,3,5,6,4]] Expected: 5

Approach: Binary Search

Compare the middle element with its right neighbor. If nums[mid] > nums[mid + 1], a peak must exist in the left half (including mid) since values are decreasing. Otherwise, a peak exists in the right half. The boundary conditions guarantee at least one peak on each side of any descent.

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)

Saved in this browser only. Private to you.

JavaScript