Valid Mountain Array - Problem

Given an array of integers arr, return true if and only if it is a valid mountain array.

Recall that arr is a mountain array if and only if:

  • arr.length >= 3
  • There exists some i with 0 < i < arr.length - 1 such that:
    • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
    • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

This means the array must strictly increase to a peak, then strictly decrease.

Input & Output

Example 1 — Valid Mountain
$ Input: arr = [0,1,2,3,4,5,4,3,2,1,0]
Output: true
💡 Note: This array strictly increases from 0 to 5, then strictly decreases from 5 to 0, forming a valid mountain with peak at index 5.
Example 2 — No Peak
$ Input: arr = [2,1]
Output: false
💡 Note: Array length is less than 3, so cannot be a mountain. Also, it only decreases without any increase.
Example 3 — Only Increasing
$ Input: arr = [1,2,3,4,5]
Output: false
💡 Note: Array only increases without any decreasing part. A mountain must have both uphill and downhill sections.

Constraints

  • 1 ≤ arr.length ≤ 104
  • 0 ≤ arr[i] ≤ 104

Visualization

Tap to expand
Valid Mountain Array INPUT Peak (i=5) arr[] = [0,1,2,3,4,5,4,3,2,1,0] idx: 0 1 2 3 4 5 6 7 8 9 10 Ascending Descending Length: 11 (>= 3) OK ALGORITHM STEPS 1 Check Length arr.length >= 3 11 >= 3 : OK 2 Climb Up Walk uphill while arr[i] < arr[i+1] 0<1<2<3<4<5 Stop at i=5 3 Verify Peak Peak not at start/end 0 < 5 < 10 : OK 4 Climb Down Walk downhill while arr[i] > arr[i+1] 5>4>3>2>1>0 Reach end! Two Pointer Approach Single pass O(n), O(1) space FINAL RESULT true Valid Mountain Verification: [OK] Length >= 3 [OK] Strict increase [OK] Peak in middle [OK] Strict decrease Key Insight: Use two-pointer technique: start from index 0 and walk up while strictly increasing. Then walk down while strictly decreasing. If you reach the end AND the peak wasn't at the first or last position, it's a valid mountain. Time: O(n), Space: O(1). TutorialsPoint - Valid Mountain Array | Optimal Solution
Asked in
Google 15 Amazon 12
28.0K Views
Medium Frequency
~15 min Avg. Time
950 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