Monotonic Array

Xavier Carty
1 min readSep 5, 2020

What is a monotonic array?

An array is monotonic if it is either monotone increasing or monotone decreasing.

Example …

Input: [1,2,2,3]
Output: true
Input: [1,3,2]
Output: false
Input: [1,2,4,5]
Output: true

As you can see it is only monotonic if the array is strictly increasing or strictly decreasing. How do we solve this ? Simple , we set two boolean values, to see if it is either decreasing or increasing.

var isMonotonic = function(A) {
let increasing = true
let decreasing = true

Next we have to check if the element before the current element or the element next to the current element is increasing or decreasing. If it is not we increasing we set increasing to false and if it is decreasing we set the decreasing value to false.

for(let i = 0; i < A.length; i++){

if(A[i] > A[i+1]){
increasing = false
}

if(A[i] < A[i+1]){
decreasing = false
}

}

Then we check if it is either increasing or decreasing. and return that value.

return increasing || decreasing 
};

That is all. You can check this problem out on Leetcode and solve it. Here is the full code

var isMonotonic = function(A) {
let increasing = true
let decreasing = true

for(let i = 0; i < A.length; i++){

if(A[i] > A[i+1]){
increasing = false
}

if(A[i] < A[i+1]){
decreasing = false
}

}

return increasing || decreasing
};

--

--

Xavier Carty

Learning new things everyday and sharing them with them world. Software Engineering , Muay Thai , and Soccer are my passions.