We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find the Peaks

Number: 3221

Difficulty: Easy

Paid? No

Companies: Bloomberg, Accelya


Problem Description

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 considered peaks. Return an array containing the indices of all peaks in any order.


Key Insights

  • The first and last elements are excluded from being peaks.
  • A peak must be strictly greater than both its left and right neighbors.
  • Iterate through the array once, starting from the second element and ending the iteration at the second-last element.
  • The problem can be efficiently solved in O(n) time, with O(p) space for collecting the peak indices, where p is the number of peaks.

Space and Time Complexity

Time Complexity: O(n), where n is the number of elements in the mountain array. Space Complexity: O(p), where p is the number of peaks stored in the result (worst-case O(n) if all non-boundary elements are peaks).


Solution

The solution involves iterating through the array starting from index 1 and ending at index n-2. For each element, we check if it is strictly greater than its immediate neighbors (elements at i-1 and i+1). If it is, we add its index to our result list. This process ensures we correctly capture all peak indices in a single pass, resulting in efficient linear time complexity and minimal space usage beyond the output array.


Code Solutions

# Function to find the peaks in the mountain array
def find_peaks(mountain):
    # List to hold indices of peaks
    peaks = []
    # Iterate from the second element to the second last element
    for i in range(1, len(mountain) - 1):
        # Check if current element is strictly greater than its left and right neighbors
        if mountain[i] > mountain[i - 1] and mountain[i] > mountain[i + 1]:
            peaks.append(i)
    # Return the list of peak indices
    return peaks

# Example usage:
mountain = [1, 4, 3, 8, 5]
print(find_peaks(mountain))  # Expected Output: [1, 3]
← Back to All Questions