I recently came across a problem that asked to create a function that will check whether or not an array is monotonic.
At first glance…. I had no idea what a monotonic array was so here’s a simple explanation.
A monotonic array is an array that has elements in a completely non-increasing or non-decreasing manner. But wait…. what does that mean?
Non-increasing elements aren’t exclusively decreasing, simply put, they just don’t increase (but you can have elements repeat, consecutively, technically the elements are not increasing if it repeats itself).
And likewise, Non-decreasing elements aren’t exclusively increasing, they just don’t decrease. Elements are allowed to repeat, as long as it’s consecutive.
Let’s get started with the problem and see how we can solve it.
Write a function that takes in an array of integers and returns a boolean representing whether the array is monotonic.
Note → Empty arrays and array’s of one element are monotonic.
How can we get started with this?
Since we’re using boolean values, I think that we can create some variables representing non-increasing/non-decreasing, and set it to true (initially).
Now that we created those variables, we need to make a comparison.
First, we need to set up a for loop and iterate over the array. Only within the for loop, can we compare the elements of the array.
Now, within the for loop, we can initialize if statements to compare consecutive values of the array. We start with the index, i, set to 1, meaning the second element of the array. We’ll compare it to the element before and check if the element at position [i] is greater than or less than the element at position [i-1]. Let’s see how that looks in code.
Now that the conditional logic is done, we just need to return the boolean value of the variables we initially created.
And with that, the solution for this problem is complete.
The time complexity of this solution is O(n) time, where (n) is the length of the array.
The space complexity of this solution is O(1) constant space.