Find the Peaks - Problem

You are given a 0-indexed array mountain. Your task is to find all the peaks in the mountain array.

Return an array that consists of indices of peaks in the given array in any order.

Notes:

  • A peak is defined as an element that is strictly greater than its neighboring elements.
  • The first and last elements of the array are not a peak.

Input & Output

Example 1 — Basic Case
$ Input: mountain = [2,4,6,3,1]
Output: [2]
💡 Note: Element at index 2 (value 6) is greater than both neighbors: 6 > 4 and 6 > 3
Example 2 — Multiple Peaks
$ Input: mountain = [1,4,3,8,5]
Output: [1,3]
💡 Note: Index 1: 4 > 1 and 4 > 3. Index 3: 8 > 3 and 8 > 5
Example 3 — No Peaks
$ Input: mountain = [1,2,3]
Output: []
💡 Note: Only one interior element at index 1: 2 > 1 but 2 < 3, so not a peak

Constraints

  • 3 ≤ mountain.length ≤ 1000
  • 1 ≤ mountain[i] ≤ 104

Visualization

Tap to expand
Find the Peaks - Single Pass Optimization INPUT Mountain Array Visualization 2 4 6 PEAK! 3 1 i=0 i=1 i=2 i=3 i=4 Input Array: mountain = [2, 4, 6, 3, 1] ALGORITHM STEPS 1 Initialize Create empty result array 2 Loop i = 1 to n-2 Skip first and last elements 3 Check Peak Condition m[i] > m[i-1] AND m[i] > m[i+1] 4 Add to Result If peak, add index i Example: i=2 m[2]=6 > m[1]=4 ? YES m[2]=6 > m[3]=3 ? YES Peak found at index 2! FINAL RESULT Peak Detection Result 2 0 4 1 6 2 3 3 1 4 PEAK Output: [2] Status: OK Found 1 peak at index 2 Key Insight: Single Pass Optimization: Iterate through array once (excluding first and last elements). For each element, check if it's strictly greater than BOTH neighbors. Time: O(n), Space: O(1). First and last elements can NEVER be peaks since they only have one neighbor. TutorialsPoint - Find the Peaks | Single Pass Optimization
Asked in
Google 15 Amazon 12 Microsoft 8
25.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen