EasyNo. 2951

Find the Peaks — LeetCode 2951 Python Solution

Topics
Array, Enumeration
Reading time
2 min

The problem

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

Example

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.

Python solution

PythonSolution
class Solution:
    def findPeaks(self, mountain: List[int]) -> List[int]:
        return [
            i
            for i in range(1, len(mountain) - 1)
            if mountain[i - 1] < mountain[i] > mountain[i + 1]
        ]

Complexity

Time
O(n)where n is the length of the array
Space · auxiliary
O(1)

Related problems

Frequently asked questions

How hard is LeetCode 2951. Find the Peaks?

LeetCode 2951. Find the Peaks is rated Easy on LeetCode.

What is the time complexity of LeetCode 2951. Find the Peaks?

The Python solution on this page runs in O(n), where n is the length of the array.

What is the space complexity of LeetCode 2951. Find the Peaks?

The Python solution on this page uses O(1) auxiliary space.

What topics does LeetCode 2951. Find the Peaks cover?

LeetCode 2951. Find the Peaks is tagged Array and Enumeration on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.