Monotonic Array
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
Single element.
Non-decreasing.
Increases then decreases.
Empty.
Non-increasing.
Algorithm Flow

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.
Time O(n), Space O(1).
Best Answers
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
