09 Sept 2026Go / Python / TypeScriptEasy

Monotonic Array

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.

complexity

O(n) time and O(1) space.

solution files

  • Go monotonic-array/solution.go
  • Python monotonic-array/solution.py
  • TypeScript monotonic-array/solution.ts

Solution files

Gomonotonic-array/solution.go
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
}
Pythonmonotonic-array/solution.py
class Solution:
    def isMonotonic(self, nums: list[int]) -> bool:
        nondecreasing = all(nums[index] >= nums[index - class="syntax-number">1] for index in range(class="syntax-number">1, len(nums)))
        nonincreasing = all(nums[index] <= nums[index - class="syntax-number">1] for index in range(class="syntax-number">1, len(nums)))
        return nondecreasing or nonincreasing
TypeScriptmonotonic-array/solution.ts
function isMonotonic(nums: number[]): boolean {
  let nondecreasing = true;
  let nonincreasing = true;
  for (let index = class="syntax-number">1; index < nums.length; index += class="syntax-number">1) { if (nums[index] < nums[index - class="syntax-number">1]) nondecreasing = false; if (nums[index] > nums[index - class="syntax-number">1]) nonincreasing = false; }
  return nondecreasing || nonincreasing;
}