Monotonic Array (LeetCode 896): Solution and Explanation
Decide whether an integer array never decreases or never increases from left to right. Flat stretches are allowed in either case.
Intuition
The definition talks about every pair i <= j, but checking all pairs is O(n^2) and unnecessary. If every adjacent step is non-decreasing, then by chaining those steps every later element is at least every earlier one. So only neighbours need checking.
You do not know in advance which direction the array is supposed to go. Instead of guessing from the first two elements, which breaks on leading equal values like [2,2,1], keep both possibilities alive at once.
Two flags do this. A step up proves the array is not non-increasing, a step down proves it is not non-decreasing, and a flat step proves nothing. At the end, the array is monotonic if at least one flag is still true.
Approach: One pass with two direction flags
- Set
increasing = Trueanddecreasing = True. - For each
ifrom 1 to n - 1, comparenums[i]withnums[i - 1]. - If it is larger, set
decreasing = False. If it is smaller, setincreasing = False. - Return
increasing or decreasing.
Step-by-step example
nums = [1,2,2,3]
- Start with both flags true.
- 1 to 2 goes up, so
decreasingbecomes false. - 2 to 2 is flat, so nothing changes.
- 2 to 3 goes up again;
decreasingis already false. increasingis still true, so the answer is true.
Code: Python, Java, C++
1class Solution:
2 def isMonotonic(self, nums: List[int]) -> bool:
3 increasing = decreasing = True
4 for i in range(1, len(nums)):
5 if nums[i] > nums[i - 1]:
6 decreasing = False
7 elif nums[i] < nums[i - 1]:
8 increasing = False
9 return increasing or decreasing1class Solution {
2 public boolean isMonotonic(int[] nums) {
3 boolean increasing = true, decreasing = true;
4 for (int i = 1; i < nums.length; i++) {
5 if (nums[i] > nums[i - 1]) {
6 decreasing = false;
7 } else if (nums[i] < nums[i - 1]) {
8 increasing = false;
9 }
10 }
11 return increasing || decreasing;
12 }
13}1class Solution {
2public:
3 bool isMonotonic(vector<int>& nums) {
4 bool increasing = true, decreasing = true;
5 for (int i = 1; i < (int)nums.size(); i++) {
6 if (nums[i] > nums[i - 1]) {
7 decreasing = false;
8 } else if (nums[i] < nums[i - 1]) {
9 increasing = false;
10 }
11 }
12 return increasing || decreasing;
13 }
14};Time and space complexity
O(n)
Each adjacent pair is compared once.
O(1)
Only the two boolean flags are stored.
Other approaches
Two separate passes (time O(n), space O(1))
Check whether the array is non-decreasing in one loop and non-increasing in another, and return true if either holds. Same complexity, slightly more code.
Direction from the endpoints (time O(n), space O(1))
Compare nums[0] with nums[n-1] to fix the only direction that can work, then verify every step goes that way or is flat. Also one pass.
Compare with a sorted copy (time O(n log n), space O(n))
Sort a copy and check whether the array equals it or its reverse. Easy to write but slower and uses extra memory.
Common mistakes
- Picking the direction from nums[0] and nums[1]. If they are equal, that comparison says nothing, and [2,2,1] would be misjudged.
- Treating equal neighbours as a violation. Monotonic here means non-strict, so flat steps are always fine.
- Returning false for a single element or an all-equal array. Both are monotonic in both directions.
- Returning
increasing and decreasing. That only accepts constant arrays; the condition is or.
Frequently asked questions
Why is checking adjacent pairs enough?
Ordering relations chain. If a <= b and b <= c, then a <= c. So if every neighbouring step is non-decreasing, every pair i <= j is too.
Can the loop stop early?
Yes. Once both flags are false, the answer is already false, so you can return immediately. It does not change the worst case.
Is an array with all equal values monotonic?
Yes. Every step is flat, so both flags stay true and the function returns true.