Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Valid Mountain Array in Python
A valid mountain array is an array that rises to a peak and then falls, resembling a mountain shape. To be valid, it must have at least 3 elements, strictly increase to a peak, then strictly decrease.
Mountain Array Requirements
An array is a valid mountain if it satisfies these conditions:
- Array size >= 3
- There exists a peak index i where:
- Elements strictly increase: A[0]
- Elements strictly decrease: A[i] > A[i+1] > ... > A[length-1]
Algorithm Approach
We use a two-phase traversal approach:
- Ascending phase: Walk up while elements are increasing
- Descending phase: Walk down while elements are decreasing
- Validation: Check if we reached the end after both phases
Implementation
def validMountainArray(A):
if len(A) < 3:
return False
i = 1
# Walk up - ascending phase
while i < len(A) and A[i] > A[i-1]:
i += 1
# Peak cannot be at start or end
if i == 1 or i == len(A):
return False
# Walk down - descending phase
while i < len(A) and A[i] < A[i-1]:
i += 1
# Should reach the end
return i == len(A)
# Test examples
print(validMountainArray([0, 3, 2, 1])) # Valid mountain
print(validMountainArray([3, 5, 5])) # Plateau - invalid
print(validMountainArray([0, 1, 2, 3])) # Only ascending
print(validMountainArray([3, 2, 1, 0])) # Only descending
True False False False
Step-by-Step Explanation
Let's trace through the algorithm with example [0, 3, 2, 1]:
- Initial check: Length = 4 >= 3 ?
- Ascending phase: i=1?2 (02 stops)
- Peak validation: i=2, not at start/end ?
- Descending phase: i=2?4 (3>2>1)
- Final check: i=4 equals array length ?
Edge Cases
| Array | Result | Reason |
|---|---|---|
| [1, 2] | False | Length |
| [1, 2, 2, 3] | False | Contains plateau |
| [1, 2, 3] | False | Only ascending |
| [3, 2, 1] | False | Only descending |
Conclusion
A valid mountain array requires strict ascending followed by strict descending phases. The algorithm uses two-pointer traversal to verify both phases exist and cover the entire array.
Advertisements
