#2951

Find the Peaks

Easy
ArrayEnumeration
LeetCode ↗

Approaches

💡

Intuition

Time Space

The brute force approach checks each element in the array (except the first and last) to see if it's greater than its neighbors. This is straightforward but inefficient.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize an empty list to store peak indices.
  2. 2Step 2: Loop through the array from the second element to the second-to-last element.
  3. 3Step 3: For each element, check if it is greater than both its neighbors. If it is, add its index to the list of peaks.
  4. 4Step 4: Return the list of peak indices.
solution.py7 lines
1# Full working Python code
2mountain = [1, 4, 3, 8, 5]
3peaks = []
4for i in range(1, len(mountain) - 1):
5    if mountain[i] > mountain[i - 1] and mountain[i] > mountain[i + 1]:
6        peaks.append(i)
7print(peaks)

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.