Find Indices of Stable Mountains - Problem

There are n mountains in a row, and each mountain has a height. You are given an integer array height where height[i] represents the height of mountain i, and an integer threshold.

A mountain is called stable if the mountain just before it (if it exists) has a height strictly greater than threshold.

Note: Mountain 0 is not stable.

Return an array containing the indices of all stable mountains in any order.

Input & Output

Example 1 — Basic Case
$ Input: height = [1,2,3,4,5], threshold = 2
Output: [3,4]
💡 Note: Mountain 3 is stable because height[2] = 3 > 2. Mountain 4 is stable because height[3] = 4 > 2. Mountains 0,1,2 are not stable.
Example 2 — No Stable Mountains
$ Input: height = [2,1,1], threshold = 5
Output: []
💡 Note: No mountain is stable because height[0] = 2 ≤ 5 and height[1] = 1 ≤ 5.
Example 3 — All Mountains Stable
$ Input: height = [10,1,10,1,10], threshold = 3
Output: [1,3]
💡 Note: Mountains 1 and 3 are stable because height[0] = 10 > 3 and height[2] = 10 > 3. Mountains 2 and 4 are not stable because height[1] = 1 ≤ 3 and height[3] = 1 ≤ 3.

Constraints

  • 1 ≤ height.length ≤ 100
  • 1 ≤ height[i] ≤ 100
  • 1 ≤ threshold ≤ 100

Visualization

Tap to expand
Find Indices of Stable Mountains INPUT h=1 i=0 h=2 i=1 h=3 i=2 h=4 i=3 h=5 i=4 threshold=2 height array: 1 2 3 4 5 threshold = 2 Green = stable mountains Mountain 0 is never stable ALGORITHM STEPS 1 Initialize result = empty array 2 Loop from i=1 to n-1 Skip index 0 (never stable) 3 Check condition height[i-1] > threshold? 4 Add to result If true, append i to result Checking each mountain: i h[i-1] >2? Stable 1 1 NO -- 2 2 NO -- 3 3 YES OK 4 4 YES OK FINAL RESULT 0 1 2 3 STABLE 4 STABLE t=2 Output Array: [3, 4] Mountain 3: prev height 3 > 2 Mountain 4: prev height 4 > 2 2 stable mountains found Key Insight: A mountain at index i is stable if and only if the previous mountain (at index i-1) has height strictly greater than the threshold. We simply iterate from index 1 to n-1 and check this condition. Time: O(n), Space: O(1) TutorialsPoint - Find Indices of Stable Mountains | Optimal Solution O(n)
Asked in
Microsoft 15 Apple 12
8.5K Views
Medium Frequency
~10 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen