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
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
โ Linear Growth
Space Complexity
O(1)
Only using two pointer variables and no additional data structures
โ 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)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code