Find the Peaks - Problem

Imagine you're a mountaineer analyzing the elevation profile of a mountain range! You have an array mountain representing the heights at different points along your path. Your mission is to identify all the peaks - those special positions where the elevation is strictly higher than both neighboring points.

What makes a peak? A peak at index i must satisfy: mountain[i-1] < mountain[i] > mountain[i+1]

Important: The first and last elements cannot be peaks (you need neighbors on both sides!)

Goal: Return an array containing the indices of all peaks in any order.

Example: For [1, 4, 3, 8, 5], index 1 (value 4) and index 3 (value 8) are peaks, so return [1, 3].

Input & Output

example_1.py โ€” Basic Mountain Range
$ Input: [2, 4, 6, 3, 1]
โ€บ Output: [2]
๐Ÿ’ก Note: Only index 2 (value 6) is a peak because 4 < 6 > 3. Index 1 has 2 < 4 but 4 < 6, so not a peak.
example_2.py โ€” Multiple Peaks
$ Input: [1, 4, 3, 8, 5]
โ€บ Output: [1, 3]
๐Ÿ’ก Note: Index 1 (value 4): 1 < 4 > 3 โœ“. Index 3 (value 8): 3 < 8 > 5 โœ“. Both are peaks!
example_3.py โ€” No Peaks Edge Case
$ Input: [1, 2, 3, 4, 5]
โ€บ Output: []
๐Ÿ’ก Note: This is a strictly increasing array, so no element is greater than both neighbors. No peaks exist.

Visualization

Tap to expand
Peak Detection in Mountain Array [1, 4, 3, 8, 5]14385idx: 0idx: 1idx: 2idx: 3idx: 4Peak Analysis:โ€ข Index 1 (value 4): 1 < 4 > 3 โœ“ PEAKโ€ข Index 3 (value 8): 3 < 8 > 5 โœ“ PEAKResult: [1, 3]
Understanding the Visualization
1
Setup the Trail
We have our elevation array representing the mountain trail
2
Start Walking
Begin from position 1 (second element) since position 0 cannot be a peak
3
Check Each Position
At each position, look back and forward to see if you're higher than both neighbors
4
Mark the Peaks
Whenever you find a position higher than both neighbors, mark it as a peak
5
Complete the Journey
Continue until position n-2 (second-to-last) since the last position cannot be a peak
Key Takeaway
๐ŸŽฏ Key Insight: A single linear pass checking immediate neighbors is sufficient to find all peaks, making this an optimal O(n) solution.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

We visit each element exactly once (except first and last)

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using a few variables, result array doesn't count toward space complexity

n
2n
โœ“ Linear Space

Constraints

  • 3 โ‰ค mountain.length โ‰ค 1000
  • 1 โ‰ค mountain[i] โ‰ค 106
  • Array length is at least 3 (needed for peaks to exist)
Asked in
Google 45 Amazon 38 Meta 25 Apple 22
28.4K Views
Medium Frequency
~8 min Avg. Time
892 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