Monotonic Array
Easy · Arrays & Hashing · Explanation and code example
One Pass - II
How it works
Rather than deciding the direction upfront, we can track both possibilities simultaneously. We maintain two flags: one for whether the array could still be non-decreasing, and one for whether it could still be non-increasing. As we scan, any violation disqualifies that direction. At the end, if at least one flag remains true, the array is monotonic.
Steps
- Initialize two boolean flags:
increase = trueanddecrease = true. - Iterate through consecutive pairs
(nums[i], nums[i + 1]):- If
nums[i] > nums[i + 1], setincrease = false. - If
nums[i] < nums[i + 1], setdecrease = false.
- If
- Return
increase || decrease.
Complexity
- Time complexity:
O(n) - Space complexity:
O(1)
Things to watch for
Using Strict Inequality Instead of Non-Strict
A monotonic array allows equal consecutive elements (non-decreasing or non-increasing). Using strict comparisons like nums[i] > nums[i-1] instead of nums[i] >= nums[i-1] incorrectly rejects arrays like [1, 2, 2, 3] as non-monotonic. The condition should check for <= (non-decreasing) or >= (non-increasing) to properly handle equal adjacent values.
Checking Only One Direction
Arrays that are constant (all elements equal) are both non-decreasing and non-increasing. Returning false early when detecting a violation in one direction without checking the other leads to incorrect results. The array [5, 5, 5] should return true, but checking only for strictly increasing or strictly decreasing patterns would fail this case.
Python code example
from typing import List
class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
increase, decrease = True, True
for i in range(len(nums) - 1):
if not (nums[i] <= nums[i + 1]):
increase = False
if not (nums[i] >= nums[i + 1]):
decrease = False
return increase or decrease
C++ code example
class Solution {
public:
bool isMonotonic(vector<int>& nums) {
bool increase = true, decrease = true;
for (int i = 0; i < nums.size() - 1; ++i) {
if (!(nums[i] <= nums[i + 1])) {
increase = false;
}
if (!(nums[i] >= nums[i + 1])) {
decrease = false;
}
}
return increase || decrease;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.