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

Find Indices of Stable Mountains

Number: 3582

Difficulty: Easy

Paid? No

Companies: Google


Problem Description

Given an array of mountain heights and a threshold value, identify all mountain indices (except the first mountain) where the mountain immediately preceding them has a height strictly greater than the threshold.


Key Insights

  • Only consider mountains starting from index 1 as mountain 0 has no preceding mountain.
  • For each mountain at index i, simply check if height[i-1] > threshold.
  • The order of indices in the output array does not matter.
  • The input size is small, so a simple linear traversal is efficient.

Space and Time Complexity

Time Complexity: O(n) where n is the number of mountains
Space Complexity: O(n) in the worst-case scenario for storing the resulting indices


Solution

Use a single loop starting from index 1 (since mountain 0 is not stable). For each mountain, check if the preceding mountain's height is greater than the threshold. If the condition is met, add the current mountain's index to the result list. This approach leverages constant-time comparisons and a simple list/dynamic array insertion.


Code Solutions

# Function to find stable mountain indices
def find_stable_mountains(height, threshold):
    stable_indices = []  # List to store indices of stable mountains
    # Loop starting from 1 since mountain 0 has no preceding mountain
    for i in range(1, len(height)):
        # If the previous mountain's height is strictly greater than the threshold, it's stable
        if height[i - 1] > threshold:
            stable_indices.append(i)
    return stable_indices

# Example usage
if __name__ == "__main__":
    height = [1, 2, 3, 4, 5]
    threshold = 2
    print(find_stable_mountains(height, threshold))  # Output: [3, 4]
← Back to All Questions