Walk up the increasing slope, reject endpoint peaks, then walk down and require reaching the final element.
Complexity
O(n) time and O(1) space.
Check whether an array strictly rises to an interior peak and then strictly falls.
Walk up the increasing slope, reject endpoint peaks, then walk down and require reaching the final element.
O(n) time and O(1) space.
package main
func validMountainArray(arr []int) bool {
index := 0
for index+1 < len(arr) && arr[index] < arr[index+1] {
index++
}
if index == 0 || index == len(arr)-1 {
return false
}
for index+1 < len(arr) && arr[index] > arr[index+1] {
index++
}
return index == len(arr)-1
}
class Solution:
def validMountainArray(self, arr: list[int]) -> bool:
index = 0
while index + 1 < len(arr) and arr[index] < arr[index + 1]: index += 1
if index == 0 or index == len(arr) - 1: return False
while index + 1 < len(arr) and arr[index] > arr[index + 1]: index += 1
return index == len(arr) - 1
function validMountainArray(arr: number[]): boolean {
let index = 0;
while (index + 1 < arr.length && arr[index] < arr[index + 1]) index += 1;
if (index === 0 || index === arr.length - 1) return false;
while (index + 1 < arr.length && arr[index] > arr[index + 1]) index += 1;
return index === arr.length - 1;
}