Difficulty: Easy | Acceptance: 86.90% | Paid: No Topics: Array
There are n mountains in a row, where mountain i has height height[i].
A mountain is called stable if its height is strictly greater than the height of the mountain immediately to its left. However, the first mountain (index 0) cannot be stable because there is no mountain to its left.
Return an array containing the indices of all stable mountains in any order.
Examples
Input: height = [1,2,3,4,5], threshold = 2
Output: [2,3,4]
Explanation:
- height[2] = 3 > 2
- height[3] = 4 > 2
- height[4] = 5 > 2
Input: height = [10,1,10,1,10], threshold = 3
Output: [2,4]
Explanation:
- height[2] = 10 > 3
- height[4] = 10 > 3
Input: height = [10,1,10,1,10], threshold = 10
Output: []
Explanation: No mountain has height strictly greater than 10.
Constraints
2 <= height.length <= 100
1 <= height[i] <= 100
1 <= threshold <= 100
Examples
Input: height = [1,2,3,4,5], threshold = 2
Output: [2,3,4]
Explanation:
- height[2] = 3 > 2
- height[3] = 4 > 2
- height[4] = 5 > 2
Input: height = [10,1,10,1,10], threshold = 3
Output: [2,4]
Explanation:
- height[2] = 10 > 3
- height[4] = 10 > 3
Input: height = [10,1,10,1,10], threshold = 10
Output: []
Explanation: No mountain has height strictly greater than 10.
Constraints
2 <= height.length <= 100
1 <= height[i] <= 100
1 <= threshold <= 100
Iterative Linear Scan
Intuition Iterate through the array starting from index 1, collecting indices where the height exceeds the threshold.
Steps
- Initialize an empty result list
- Loop from index 1 to end of array
- If height[i] > threshold, add index i to result
- Return the result list
python
from typing import List
class Solution:
def stableMountains(self, height: List[int], threshold: int) -> List[int]:
result = []
for i in range(1, len(height)):
if height[i] > threshold:
result.append(i)
return resultComplexity
- Time: O(n) where n is the length of height array
- Space: O(k) where k is the number of stable mountains (for output)
- Notes: Simple and efficient, single pass through the array
Functional Approach
Intuition Use language-specific functional programming features like list comprehension, streams, or filter/map to concisely filter stable mountain indices.
Steps
- Generate indices from 1 to n-1
- Filter indices where height[i] > threshold
- Return the filtered result
python
from typing import List
class Solution:
def stableMountains(self, height: List[int], threshold: int) -> List[int]:
return [i for i in range(1, len(height)) if height[i] > threshold]Complexity
- Time: O(n) where n is the length of height array
- Space: O(k) where k is the number of stable mountains (for output)
- Notes: More concise syntax, but same underlying complexity as iterative approach