Monotonic Array | LeetCode 896 | Python | Solution

Here is the link to the problem. See the problem description.

We have to check the given array is monotonic or not.

What is a monotonic array?

“An array is monotonic if it is either monotone increasing or monotone decreasing.” line quoted from the problem description.

The formula is:
For checking increasing monotone of the given array: current_element <= current_element.

For checking decreasing monotone of the given array: current_element >= next_element.

The given array must be monotonic, either increasing or decreasing way. Otherwise, we will return False.

So, to solve this problem, we will define two variables with the initial value True. Then we will run a loop till the second last element of the given array. Because each time, we have to check the current element with the current’s next element. See the logic inside the loop in the code example.

After the loop, if one of the variable’s values remains True, we can say that it is a monotonic array.

class Solution:
    def isMonotonic(self, A: List[int]) -> bool:
        increasing = True
        decreasing = True
        for i in range(len(A)-1):
            if A[i] > A[i+1]:
                increasing = False
            if A[i] < A[i+1]:
                decreasing = False
        return increasing or decreasing

I hope the above solution will help you to understand the problem in more detail.