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
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]
false
as it cannot form a mountain array.def validMountainArray(arr):
n = len(arr)
if n < 3:
return False
left, right = 0, n - 1
# Climb up from left
while left + 1 < n and arr[left] < arr[left + 1]:
left += 1
# Climb up from right
while right - 1 >= 0 and arr[right] < arr[right - 1]:
right -= 1
# left and right should point to the same peak index
return left > 0 and right < n - 1 and left == right
# Example usage
arr = [2, 1]
print(validMountainArray(arr)) # Output: False
arr = [3, 5, 5]
print(validMountainArray(arr)) # Output: False
arr = [0, 3, 2, 1]
print(validMountainArray(arr)) # Output: True
O(n)
, where n
is the length of the array. We traverse the array with two pointers in a single pass.O(1)
, as we use a constant amount of additional memory regardless of the input size.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?