Find the Peaks
Problem
You are given a 0-indexed array mountain. Your task is to find all the peaks in the mountain array. 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 peaks. Return the indices of all peaks in any order.
mountain = [1,4,3,8,5][1,3]def find_peaks(mountain):
peaks = []
for i in range(1, len(mountain) - 1):
if mountain[i] > mountain[i - 1] and mountain[i] > mountain[i + 1]:
peaks.append(i)
return peaks
function findPeaks(mountain) {
const peaks = [];
for (let i = 1; i < mountain.length - 1; i++) {
if (mountain[i] > mountain[i - 1] && mountain[i] > mountain[i + 1]) {
peaks.push(i);
}
}
return peaks;
}
class Solution {
public List<Integer> findPeaks(int[] mountain) {
List<Integer> peaks = new ArrayList<>();
for (int i = 1; i < mountain.length - 1; i++) {
if (mountain[i] > mountain[i - 1] && mountain[i] > mountain[i + 1]) {
peaks.add(i);
}
}
return peaks;
}
}
vector<int> findPeaks(vector<int>& mountain) {
vector<int> peaks;
for (int i = 1; i < (int)mountain.size() - 1; i++) {
if (mountain[i] > mountain[i - 1] && mountain[i] > mountain[i + 1]) {
peaks.push_back(i);
}
}
return peaks;
}
Explanation
A peak is a position that is strictly taller than both immediate neighbors. By definition the first and last elements have only one neighbor, so they can never qualify and are skipped.
That means we only inspect the interior indices, from 1 to n-2 inclusive. For each such index i we compare it against i-1 and i+1.
The condition is two strict greater-than checks joined with AND: mountain[i] > mountain[i-1] and mountain[i] > mountain[i+1]. Strict comparisons matter — a value equal to a neighbor is a plateau, not a peak.
Whenever both checks pass we record the index. Because every interior index is examined independently, we can find multiple peaks in a single left-to-right pass with no extra state.
Example: [1,4,3,8,5]. Index 1 has 4 > 1 and 4 > 3 → peak. Index 2 fails (3 < 4). Index 3 has 8 > 3 and 8 > 5 → peak. Result: [1,3].