Description
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
iwith0 < i < arr.length - 1such that:arr[0] < arr[1] < ... < arr[i - 1] < arr[i]arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Constraints
1 <= nums.length <= 104-231 <= nums[i] <= 231 - 1
Examples
- Example 1:
Input:arr = [2, 1]Output:false - Example 2:
Input:arr = [3, 5, 5]Output:false - Example: 3
Input:arr = [0, 3, 2, 1]Output:true
Solution 1: One Pass
Steps
- Base Case: According to the definition of a mountain array, if the length of the array
arris less than 3 or ifarris in a descending state from the beginning (arr[0] > arr[1]), we can directly returnFalsehere. - Declare a variable
peak_reachedto indicate whether we have reached the peak. - Iterate through the
arr:- If the current element
arr[i]is equal to the next elementarr[i + 1], according to the definition, this is an invalid mountain array, so we can directly returnFalsehere. - If the current element
arr[i]is greater than the next elementarr[i + 1], it means we have reached the peak, and the subsequent elements can only be in descending order. Setpeak_reachedtoTruein this case. - Otherwise, if we have already reached the peak (
peak_reachedisTrue), but the current elementarr[i]is smaller than the next elementarr[i + 1], it means we are climbing the mountain again, which is invalid according to the definition of a mountain array. In this case, we can directly returnFalse.
- If the current element
- After the iteration is complete, return
peak_reachedto ensure that we have reached the peak at some point because a strictly increasing (monotone increasing) array is not a valid mountain array.
Codes
def valid_mountain_array(arr: List[int]) -> bool:
if len(arr) < 3 or arr[0] > arr[1]:
return False
peak_reached = False
for i in range(len(arr) - 1):
if arr[i] == arr[i + 1]:
return False
elif arr[i] > arr[i + 1]:
peak_reached = True
else:
if peak_reached:
return False
return peak_reachedPythonComplexities
- Time Complexity:
O(N), whereNis the length of thearrarray. - Space Complexity:
O(1)
References
- LeetCode link: Valid Mountain Array – LeetCode