Valid Mountain Array - Problem

Imagine you're a cartographer tasked with validating topographical data! ๐Ÿ”๏ธ You need to determine if an array of integers represents a valid mountain array.

A mountain array has these characteristics:

  • It must have at least 3 elements (you can't have a mountain with just 1-2 points!)
  • There exists a peak somewhere in the middle (not at the edges)
  • Elements strictly increase up to the peak: arr[0] < arr[1] < ... < arr[peak]
  • Elements strictly decrease after the peak: arr[peak] > arr[peak+1] > ... > arr[n-1]

Goal: Return true if the array forms a valid mountain, false otherwise.

Remember: A valid mountain must go UP first, then DOWN. It cannot have plateaus (equal adjacent elements) or multiple peaks!

Input & Output

example_1.py โ€” Valid Mountain
$ Input: [2,1]
โ€บ Output: false
๐Ÿ’ก Note: This array is too short (length < 3) and only decreases, so it cannot be a valid mountain.
example_2.py โ€” Valid Mountain
$ Input: [3,5,5]
โ€บ Output: false
๐Ÿ’ก Note: This has a plateau (5,5) which violates the strictly increasing/decreasing requirement.
example_3.py โ€” Valid Mountain
$ Input: [0,1,2,3,4,3,2,1,0]
โ€บ Output: true
๐Ÿ’ก Note: This forms a perfect mountain: increases from 0 to 4, then decreases from 4 to 0.

Visualization

Tap to expand
Mountain Validation: Two Hikers ApproachPEAKLEFT HIKERRIGHT HIKERBoth hikers meet at the peak = Valid Mountain! โœ“
Understanding the Visualization
1
Start the Journey
Left hiker starts climbing up, right hiker starts going down
2
Keep Moving
Each hiker continues as long as the path keeps going their direction
3
Find the Meeting Point
Both hikers stop when they can't continue - do they meet at the same spot?
4
Validate the Mountain
Valid mountain if they meet in the middle and both actually moved
Key Takeaway
๐ŸŽฏ Key Insight: A valid mountain can be efficiently detected by checking if ascending from left and descending from right meet at the same peak position!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the array with two pointers meeting in the middle

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using two pointer variables and no additional data structures

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค arr.length โ‰ค 104
  • 0 โ‰ค arr[i] โ‰ค 104
  • Array must have exactly one peak (not at edges)
  • No plateaus allowed (strictly increasing/decreasing)
Asked in
Facebook 25 Amazon 18 Google 15 Microsoft 12
26.7K Views
Medium Frequency
~15 min Avg. Time
890 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