Talentd
FleetCode
Make and follow sheets.Sign in

Find the Peaks solution and explanation

EasyArrayEnumeration6 min read75.5% acceptanceUpdated 9 Apr 2026
Solving Leetcode 2951 in Swift – Find the PeaksBABE ENGINEER · 6:11 · 1K viewsWatch on YouTube
9 more videos on this problem
  1. Solving Leetcode 2951 in Swift – Find the PeaksBABE ENGINEER · 6:11 · 1K views
  2. 2951. Find the Peaks || Java || Leetcode || HindiCoding Sphere · 4:13 · 414 views
  3. 2951. Find the Peaks (Leetcode Easy)Programming Live with Larry · 2:11 · 161 views
  4. 2951 ) Find the peaks in Arrays | Leetcode | Qn no:2951Code Galaxy · 2:22 · 147 views
  5. Leetcode Problem Solving #2951 - Find the Peaks✅ | #leetcode | #coding | #KrishCodesKrishCodes · 9:33 · 96 views
  6. 2951. Find the Peaks | Weekly Contest 374 | Leetcode | Lets practice togetherLet's Practice Together · 2:50 · 91 views
  7. 2951. Find the Peaks | Weekly Contest 374Tech Courses · 2:42 · 91 views
  8. 🚀 Leetcode 2951 | Find the Peaks | Optimized Solutionrio_jaggu · 4:31 · 58 views
  9. 2951. Find the Peaks | Leetcode Problem Solving CPPNishit · 5:23 · 21 views
  10. my attempt at solving leetcode 2951: find the peaks [SOLVED]Cameron Late · 6:49 · 16 views

The 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.

Example 1:

Input: mountain = [2,4,4]
Output: []
Explanation: mountain[0] and mountain[2] can not be a peak because they are first and last elements of the array.
mountain[1] also can not be a peak because it is not strictly greater than mountain[2].
So the answer is [].

Example 2:

Input: mountain = [1,4,3,8,5]
Output: [1,3]
Explanation: mountain[0] and mountain[4] can not be a peak because they are first and last elements of the array.
mountain[2] also can not be a peak because it is not strictly greater than mountain[3] and mountain[1].
But mountain [1] and mountain[3] are strictly greater than their neighboring elements.
So the answer is [1,3].

Constraints:

  • 3 <= mountain.length <= 100
  • 1 <= mountain[i] <= 100

Approach overview

Problem Overview: You are given an integer array mountain. A peak is an index i such that mountain[i] is strictly greater than both neighbors: mountain[i-1] and mountain[i+1]. The first and last elements cannot be peaks because they do not have two neighbors. Your task is to return all indices that satisfy this condition.

Approach 1: Brute Force Neighbor Check (O(n) time, O(1) extra space)

The straightforward approach is to iterate through the array and check each valid index against its immediate neighbors. Start from index 1 and stop at n-2. For every index i, compare mountain[i] with mountain[i-1] and mountain[i+1]. If the current value is strictly greater than both, record i in the result list.

This method directly follows the problem definition. It performs two comparisons per index and uses only a result container to store peak indices. Since each element is checked once, the time complexity is O(n) and the auxiliary space (excluding output) is O(1). This approach is simple and reliable for small and large inputs alike.

Approach 2: Optimized Single Pass Enumeration (O(n) time, O(1) extra space)

The optimized version treats the problem as a single-pass scan over the array using array traversal and enumeration. Instead of thinking of it as a repeated "check," you maintain a forward iteration and evaluate the peak condition inline during traversal.

Initialize an empty list for the results and loop from i = 1 to n - 2. For each position, perform two comparisons: check whether the current value is greater than the previous element and the next element. When both conditions hold, append the index to the result. The algorithm performs exactly one pass and does not require additional data structures.

The complexity remains O(n) time and O(1) extra space because each element is visited once and only constant additional memory is used. The difference from the brute-force mindset is conceptual clarity: this approach frames the problem as a clean linear scan with constant checks, which is how most interview solutions are written.

Recommended for interviews: The single-pass enumeration approach is what interviewers expect. It demonstrates that you can translate the definition of a peak directly into a linear scan using simple comparisons. Mentioning the brute-force reasoning first shows you understand the problem constraints, but implementing the O(n) single-pass solution highlights strong fundamentals with arrays and efficient iteration patterns.

Approach 1: Brute Force Approach

This approach involves iterating through the given array and checking each element to find the peaks. A peak is defined as an element that is strictly greater than its neighboring elements. Specifically, an element at index i is a peak if mountain[i] > mountain[i-1] and mountain[i] > mountain[i+1]. We must ensure that we do not check the first or last elements, as they cannot be peaks. The time complexity of this approach is O(n), where n is the number of elements in the mountain array, because we make one pass through the array. The space complexity is O(1), as we use a constant amount of extra memory.

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

mountain = [1, 4, 3, 8, 5]
peaks = find_peaks(mountain)
print("Peaks at indices:", peaks)
import java.util.ArrayList;
import java.util.List;

public class Peaks {
    public static 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;
    }

    public static void main(String[] args) {
        int[] mountain = {1, 4, 3, 8, 5};
        List<Integer> peaks = findPeaks(mountain);
        System.out.println("Peaks at indices: " + peaks);
    }
}
#include <iostream>
#include <vector>
using namespace std;

vector<int> findPeaks(vector<int>& mountain) {
    vector<int> peaks;
    for (int i = 1; i < mountain.size() - 1; ++i) {
        if (mountain[i] > mountain[i - 1] && mountain[i] > mountain[i + 1]) {
            peaks.push_back(i);
        }
    }
    return peaks;
}

int main() {
    vector<int> mountain = {1, 4, 3, 8, 5};
    vector<int> peaks = findPeaks(mountain);
    cout << "Peaks at indices: ";
    for (int index : peaks) {
        cout << index << " ";
    }
    return 0;
}
function findPeaks(mountain) {
    let 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;
}

const mountain = [1, 4, 3, 8, 5];
const peaks = findPeaks(mountain);
console.log('Peaks at indices:', peaks);
#include <stdio.h>
#include <stdlib.h>

int* findPeaks(int* mountain, int mountainSize, int* returnSize){
    *returnSize = 0;
    int* peaks = (int*)malloc(mountainSize * sizeof(int));
    for (int i = 1; i < mountainSize - 1; i++) {
        if (mountain[i] > mountain[i - 1] && mountain[i] > mountain[i + 1]) {
            peaks[(*returnSize)++] = i;
        }
    }
    return peaks;
}

int main() {
    int mountain[] = {1, 4, 3, 8, 5};
    int returnSize;
    int *peaks = findPeaks(mountain, 5, &returnSize);
    printf("Peaks at indices: ");
    for (int i = 0; i < returnSize; i++) {
        printf("%d ", peaks[i]);
    }
    free(peaks);
    return 0;
}
using System;
using System.Collections.Generic;

public class Peaks {
    public static List<int> FindPeaks(int[] mountain) {
        List<int> peaks = new List<int>();
        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;
    }

    public static void Main() {
        int[] mountain = { 1, 4, 3, 8, 5 };
        List<int> peaks = FindPeaks(mountain);
        Console.WriteLine("Peaks at indices: " + string.Join(", ", peaks));
    }
}

In Python, we simply iterate over the array while avoiding the first and last elements. We append indices to the peaks list whenever we find an element that is greater than its neighbors.

Complexity

Time Complexity: O(n)
Space Complexity: O(n) in the worst case for storing peak indices.

Try this approach in the editor

Approach 2: Optimized Single Pass Approach

This approach aims to optimize by reducing redundant checks and utilizing a single iteration efficiently. Given the constraints, the optimized solution also iterates through the array but takes extra care to minimize checks by assuming certain boundaries have already been met. The time complexity is similar to the brute force approach at O(n), but we attempt to improve constant factors. The space complexity remains O(1) for constant auxiliary space, but realistic implementations use O(n) for output storage.

def find_peaks_single_pass(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

mountain = [1, 4, 3, 8, 5]
peaks = find_peaks_single_pass(mountain)
print("Peaks at indices:", peaks)
import java.util.ArrayList;
import java.util.List;

public class Peaks {
    public static List<Integer> findPeaksSinglePass(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;
    }

    public static void main(String[] args) {
        int[] mountain = {1, 4, 3, 8, 5};
        List<Integer> peaks = findPeaksSinglePass(mountain);
        System.out.println("Peaks at indices: " + peaks);
    }
}
#include <iostream>
#include <vector>
using namespace std;

vector<int> findPeaksSinglePass(vector<int>& mountain) {
    vector<int> peaks;
    for (int i = 1; i < mountain.size() - 1; ++i) {
        if (mountain[i] > mountain[i - 1] && mountain[i] > mountain[i + 1]) {
            peaks.push_back(i);
        }
    }
    return peaks;
}

int main() {
    vector<int> mountain = {1, 4, 3, 8, 5};
    vector<int> peaks = findPeaksSinglePass(mountain);
    cout << "Peaks at indices: ";
    for (int index : peaks) {
        cout << index << " ";
    }
    return 0;
}
function findPeaksSinglePass(mountain) {
    let 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;
}

const mountain = [1, 4, 3, 8, 5];
const peaks = findPeaksSinglePass(mountain);
console.log('Peaks at indices:', peaks);
#include <stdio.h>
#include <stdlib.h>

int* findPeaksSinglePass(int* mountain, int mountainSize, int* returnSize){
    *returnSize = 0;
    int* peaks = (int*)malloc(mountainSize * sizeof(int));
    for (int i = 1; i < mountainSize - 1; i++) {
        if (mountain[i] > mountain[i - 1] && mountain[i] > mountain[i + 1]) {
            peaks[(*returnSize)++] = i;
        }
    }
    return peaks;
}

int main() {
    int mountain[] = {1, 4, 3, 8, 5};
    int returnSize;
    int *peaks = findPeaksSinglePass(mountain, 5, &returnSize);
    printf("Peaks at indices: ");
    for (int i = 0; i < returnSize; i++) {
        printf("%d ", peaks[i]);
    }
    free(peaks);
    return 0;
}
using System;
using System.Collections.Generic;

public class Peaks {
    public static List<int> FindPeaksSinglePass(int[] mountain) {
        List<int> peaks = new List<int>();
        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;
    }

    public static void Main() {
        int[] mountain = { 1, 4, 3, 8, 5 };
        List<int> peaks = FindPeaksSinglePass(mountain);
        Console.WriteLine("Peaks at indices: " + string.Join(", ", peaks));
    }
}

The Python implementation iterates once over relevant elements and checks neighbors to identify peaks. List operators maintain efficient memory use and direct syntax helps keep constant factor small.

Complexity

Time Complexity: O(n)
Space Complexity: O(n) for result storage.

Try this approach in the editor

Approach 3: Direct Traversal

We directly traverse the index i \in [1, n-2]. For each index i, if mountain[i-1] < mountain[i] and mountain[i + 1] < mountain[i], then mountain[i] is a peak, and we add index i to the answer array.

After the traversal ends, we return the answer array.

The time complexity is O(n), where n is the length of the array. Ignoring the space consumption of the answer array, the space complexity is O(1).

function findPeaks(mountain: number[]): number[] {
    const ans: number[] = [];
    for (let i = 1; i < mountain.length - 1; ++i) {
        if (mountain[i - 1] < mountain[i] && mountain[i + 1] < mountain[i]) {
            ans.push(i);
        }
    }
    return ans;
}
func findPeaks(mountain []int) (ans []int) {
	for i := 1; i < len(mountain)-1; i++ {
		if mountain[i-1] < mountain[i] && mountain[i+1] < mountain[i] {
			ans = append(ans, i)
		}
	}
	return
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Brute Force Approach

Time Complexity: O(n)
Space Complexity: O(n) in the worst case for storing peak indices.

Optimized Single Pass Approach

Time Complexity: O(n)
Space Complexity: O(n) for result storage.

Direct Traversal–

Complexity analysis

ApproachTimeSpaceWhen to Use
Brute Force Neighbor CheckO(n)O(1)When implementing the definition directly or explaining the problem step-by-step in interviews.
Optimized Single Pass EnumerationO(n)O(1)Preferred production and interview solution. Clean linear scan with minimal comparisons.

Frequently asked questions

Is Find the Peaks easy or hard?

Find the Peaks is classified as an Easy problem. It focuses on basic array traversal and conditional checks rather than advanced data structures or algorithms. Most candidates solve it with a straightforward O(n) single-pass approach.

Find the Peaks Python/Java solution

The Python or Java implementation performs a loop from index 1 to n-2 and checks the two neighbor conditions. If both comparisons are true, the index is appended to a result list. The logic is identical across languages and runs in O(n) time with O(1) extra space.

How to solve Find the Peaks in O(n)?

Traverse the array from index 1 to n-2 and compare each element with its neighbors. If mountain[i] > mountain[i-1] and mountain[i] > mountain[i+1], record the index as a peak. Since every element is processed once, the algorithm runs in O(n) time with constant extra space.

What is the best approach for Find the Peaks?

The best approach is a single-pass linear scan of the array. Iterate from index 1 to n-2 and check whether each element is greater than its immediate neighbors. This solution runs in O(n) time and uses O(1) extra space, making it optimal for the problem.

Is Find the Peaks asked at Google/Amazon/Meta?

Find the Peaks reflects a common array traversal pattern frequently used in technical interviews. Variants of peak-finding and local maximum problems have appeared in interviews at companies like Google, Amazon, and Meta, especially in entry-level or screening rounds.

What data structure is used in Find the Peaks?

The primary data structure is an array. The algorithm performs sequential traversal and simple neighbor comparisons. The result is typically stored in a dynamic list or array of indices representing the peak positions.

What is the time complexity of Find the Peaks?

The time complexity is O(n) because the algorithm scans the array exactly once. For each index, it performs only two comparisons with neighboring elements. The extra space complexity is O(1) excluding the output list.

Comments

Now write it yourselfClose this page and solve Find the Peaks in the editor, without looking.
Practise Find the Peaks