Tutorialspoint
Problem
Solution
Submissions

Find Peak Element

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a JavaScript program to find a peak element in an array. A peak element is an element that is strictly greater than its neighbors. Given a 0-indexed integer array nums, find a peak element and return its index. If the array contains multiple peaks, return the index to any one of the peaks. You may imagine that nums[-1] = nums[n] = -∞. The algorithm should run in O(log n) time complexity.

Example 1
  • Input: nums = [1,2,3,1]
  • Output: 2
  • Explanation:
    • Check element at index 2, which has value 3.
    • Compare with left neighbor: 3 > 2 (at index 1).
    • Compare with right neighbor: 3 > 1 (at index 3).
    • Since 3 is greater than both neighbors, index 2 is a peak.
Example 2
  • Input: nums = [1,2,1,3,5,6,4]
  • Output: 5
  • Explanation:
    • The array has multiple peaks at indices 1 and 5.
    • Element at index 1 has value 2: 2 > 1 (left) and 2 > 1 (right).
    • Element at index 5 has value 6: 6 > 5 (left) and 6 > 4 (right).
    • Either index 1 or 5 can be returned as both are valid peaks.
Constraints
  • 1 ≤ nums.length ≤ 1000
  • -2^31 ≤ nums[i] ≤ 2^31 - 1
  • nums[i] != nums[i + 1] for all valid i
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
ArraysKPMGD. E. Shaw
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use binary search to achieve O(log n) time complexity
  • Compare the middle element with its right neighbor to determine search direction
  • If nums[mid] < nums[mid + 1], the peak must be on the right side
  • If nums[mid] > nums[mid + 1], the peak could be at mid or on the left side
  • Continue binary search until you find a peak element
  • Handle edge cases for single element array and boundary elements

Steps to solve by this approach:

 Step 1: Initialize left and right pointers to define the search range (0 to nums.length - 1).

 Step 2: Calculate the middle index using the formula mid = (left + right) / 2.
 Step 3: Compare the middle element with its right neighbor to determine the search direction.
 Step 4: If nums[mid] < nums[mid + 1], move the left pointer to mid + 1 (search right half).
 Step 5: If nums[mid] > nums[mid + 1], move the right pointer to mid (search left half including mid).
 Step 6: Continue the binary search until left equals right, which gives the peak element index.
 Step 7: Return the final index as it guaranteed to be a peak element.

Submitted Code :