Monotonic Coding Problem

Nerly Ton
1 min readApr 12, 2021

AlgoExpert — Medium

One of the problems I worked on this week was about Monotonic.

Definition

Monotonic: of a function or quantity) varying in such a way that it either never decreases or never increases.

In other words there is no change in direction. If the array begins with increasing then it ends with increasing or vise versa.

Problem:

Write a function that takes in an array of integers and returns a boolean representing whether the array is monotonic.

Solution:

For this problem we would need to set up two variables that equal true.
one for increasing and the other for decreasing.

Then we need to get rid of some edge cases for example is the array is empty then return true, or is the array’s length is 1 then return true too.

After we need to iterate through the array to check if array[i] > array[i +1] if it is then we will change increasing to false.
And then do the opposite for decreasing

At the end you will return the answer

Here is the code to get a better understanding.

function isMonotonic(array) {
// Write your code here.
let increasing = true
let decreasing = true
if(array.length === 0 || array.length === 1) {
return true
}
for(let i = 0; i < array.length; i++) {
if(array[i] > array[i + 1]) {
increasing = false
}
if (array[i + 1] > array[i]) {
decreasing = false
}
}
return increasing || decreasing
}

This solution is O(n) time and O(1) space.

--

--