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 given array is monotonic, or false otherwise. Make a single pass checking two flags at once: whether any adjacent pair breaks the non-decreasing rule, and whether any adjacent pair breaks the non-increasing rule.
Constraints
- 1 ≤ nums.length ≤ 105
- -105 ≤ numsi ≤ 105
Example
nums = [1, 2, 2, 3]trueExplanation Each value is greater than or equal to the one before it, so the array is non-decreasing.
In plain terms
- Monotonic
- Consistently moving in one direction — either every step stays the same or goes up, or every step stays the same or goes down, with no mixing of both.
Track both increasing and decreasing possibilities at once
Compare nums[0]=1 and nums[1]=2. 1 <= 2, so isIncreasing stays true; 1 < 2 breaks isDecreasing (false).
What happens in this step
nums[0]=1, nums[1]=2 1 <= 2 (isIncreasing stays true) 1 < 2 (isDecreasing becomes false)
Steps to visualize
- Start with two flags: isIncreasing = true and isDecreasing = true.
- Walk through adjacent pairs of the array.
- If a later value is smaller than an earlier one, isIncreasing becomes false.
- If a later value is larger than an earlier one, isDecreasing becomes false.
- The array is monotonic if isIncreasing or isDecreasing remains true at the end.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Compare nums[0]=1 and nums[1]=2. 1 <= 2, so isIncreasing stays true; 1 < 2 breaks isDecreasing (false).
What happens in this step
nums[0]=1, nums[1]=2 1 <= 2 (isIncreasing stays true) 1 < 2 (isDecreasing becomes false)
Solution
function isMonotonic(nums) {
let isIncreasing = true;
let isDecreasing = true;
for (let i = 1; i < nums.length; i++) {
if (nums[i] < nums[i - 1]) {
isIncreasing = false;
}
if (nums[i] > nums[i - 1]) {
isDecreasing = false;
}
}
return isIncreasing || isDecreasing;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [1, 2, 2, 3] | true | example from the docstring |
nums = [6, 5, 4, 4] | true | strictly non-increasing with a tie |
nums = [1, 3, 2] | false | array that goes up then down |
nums = [5] | true | smallest valid input, a single element is trivially monotonic |
nums = [3, 3, 3] | true | every value identical, both increasing and decreasing hold |
nums = [5, 4, 3, 2, 1] | true | strictly decreasing with no ties |