Peak Element Finder - Problem

A peak element in an array is an element that is greater than both of its neighbors. Given an integer array nums, find all peak elements and return their indices.

For edge elements (first and last elements), they are considered peaks if they are greater than their single neighbor.

Special cases:

  • If the array has only one element, it is always a peak
  • The first element is a peak if it's greater than the second element
  • The last element is a peak if it's greater than the second-to-last element

Input & Output

Example 1 — Multiple Peaks
$ Input: nums = [5,2,8,3,7,1]
Output: [0,2,4]
💡 Note: Index 0: 5 > 2 (first element peak), Index 2: 8 > 2 and 8 > 3 (middle peak), Index 4: 7 > 3 and 7 > 1 (middle peak)
Example 2 — Edge Peaks Only
$ Input: nums = [4,1,2,3]
Output: [0,3]
💡 Note: Index 0: 4 > 1 (first element is peak), Index 3: 3 > 2 (last element is peak)
Example 3 — Single Element
$ Input: nums = [7]
Output: [0]
💡 Note: Single element is always a peak by definition

Constraints

  • 1 ≤ nums.length ≤ 1000
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Peak Element Finder - Array AnalysisINPUT ARRAYALGORITHM STEPSPEAK INDICES5283710123451. Check first element5 > 2? Yes → Peak at index 02. Check middle elements8 > 2 and 8 > 3? Yes → Peak at 23. Continue checking7 > 3 and 7 > 1? Yes → Peak at 44. Complete scanAll elements checked[0, 2, 4]Peak found at indices:0: value 52: value 84: value 7Key Insight:Each element only needs comparison with immediate neighbors - no complex algorithms needed!TutorialsPoint - Peak Element Finder | Single Pass Algorithm
Asked in
Google 25 Amazon 18 Microsoft 15 Facebook 12
28.5K 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