Code Logo

Monotonic Array

Published at24 Jul 2026
Easy 0 views
Like0

An array is monotonic if it is either entirely non-increasing or entirely non-decreasing. Given an integer array nums, return true if the array is monotonic, or false otherwise.

This is a state tracking DP problem. Track two boolean flags: increasing and decreasing. Initially both are true. Iterate through adjacent pairs. If at any pair the values increase, the array cannot be non-increasing, so set decreasing to false. If they decrease, set increasing to false. After processing all pairs, if either flag is still true, the array is monotonic.

The DP state is the set of viable monotonic patterns remaining. As we process each adjacent pair, we eliminate patterns that are violated. When both patterns are eliminated, we can return false early. This is O(n) time with O(1) space.

Edge cases include empty or single-element arrays (always monotonic), all equal values (both patterns hold, return true), and arrays with both increases and decreases.

The dual-flag approach tracks two monotonic patterns simultaneously and eliminates them as violations are found. This avoids needing two separate passes for increasing and decreasing checks. The early exit optimization stops as soon as both patterns are eliminated.

Example Input & Output

Example 1
Input
[5]
Output
true
Explanation

Single element.

Example 2
Input
[1,2,2,3]
Output
true
Explanation

Non-decreasing.

Example 3
Input
[1,3,2]
Output
false
Explanation

Increases then decreases.

Example 4
Input
[]
Output
true
Explanation

Empty.

Example 5
Input
[6,5,4,4]
Output
true
Explanation

Non-increasing.

Algorithm Flow

Recommendation Algorithm Flow for Monotonic Array
Recommendation Algorithm Flow for Monotonic Array

Solution Approach

Track inc and dec flags. For each adjacent pair, if nums[i] < nums[i+1], dec=false; if nums[i] > nums[i+1], inc=false. Return inc OR dec.

function solution(nums) {
  var inc = true, dec = true;
  for (var i = 1; i < nums.length; i++) {
    if (nums[i] < nums[i-1]) inc = false;
    if (nums[i] > nums[i-1]) dec = false;
    if (!inc && !dec) return false;
  }
  return true;
}

Time O(n), Space O(1).

Best Answers

java
class Solution {
    public boolean solution(int[] nums) {
        boolean inc=true,dec=true;
        for (int i=1;i<nums.length;i++) {
            if (nums[i]<nums[i-1]) inc=false;
            if (nums[i]>nums[i-1]) dec=false;
            if (!inc && !dec) return false;
        }
        return true;
    }
}