Track whether any adjacent pair violates increasing or decreasing order; the array is monotonic while at least one direction remains possible.
Complexity
O(n) time and O(1) space.
Check whether an array is entirely nondecreasing or entirely nonincreasing.
Track whether any adjacent pair violates increasing or decreasing order; the array is monotonic while at least one direction remains possible.
O(n) time and O(1) space.
package main
func isMonotonic(nums []int) bool {
nondecreasing, nonincreasing := true, true
for index := 1; index < len(nums); index++ {
if nums[index] < nums[index-1] {
nondecreasing = false
}
if nums[index] > nums[index-1] {
nonincreasing = false
}
}
return nondecreasing || nonincreasing
}
class Solution:
def isMonotonic(self, nums: list[int]) -> bool:
nondecreasing = all(nums[index] >= nums[index - 1] for index in range(1, len(nums)))
nonincreasing = all(nums[index] <= nums[index - 1] for index in range(1, len(nums)))
return nondecreasing or nonincreasing
function isMonotonic(nums: number[]): boolean {
let nondecreasing = true;
let nonincreasing = true;
for (let index = 1; index < nums.length; index += 1) { if (nums[index] < nums[index - 1]) nondecreasing = false; if (nums[index] > nums[index - 1]) nonincreasing = false; }
return nondecreasing || nonincreasing;
}