Monotonic Array

Patrick Leaton
Problem Description

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

An array A is monotone increasing if for all i <= jA[i] <= A[j].  An array A is monotone decreasing if for all i <= jA[i] >= A[j].

Return true if and only if the given array A is monotonic.

Example 1:

Input: [1,2,2,3]
Output: true

Example 2:

Input: [6,5,4,4]
Output: true

Example 3:

Input: [1,3,2]
Output: false

Example 4:

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

Example 5:

Input: [1,1,1]
Output: true

Note:

  1. 1 <= A.length <= 50000
  2. -100000 <= A[i] <= 100000

 

The description was taken from https://leetcode.com/problems/monotonic-array/.

Problem Solution

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

Problem Explanation


With a problem like this, where there are only a couple of possible use cases like whether the array is increasing or decreasing, many times we can just make a conditional statement for each use case and approach the question that way.

We'll have one conditional statement to check if the array is decreasing, one to see if it's increasing, and continue to update these values.

In the end, we will see one of the conditions remained true.


In the description, it specifies the array is monotonic if it is strictly increasing or decreasing so we will create these two variables to store the answers.

        increasing = decreasing = True

 

We'll then traverse the array starting from the second index and see if the element behind us is higher or lower.  

        for i in range(1, len(A)):

 

If it is lower, we know we aren't decreasing.

            if A[i] > A[i-1]:
                decreasing = False

 

If it is higher, we know we aren't increasing.

            elif A[i] < A[i-1]:
                increasing = False

 

We'll return whether or not one of these two conditions remained true once we reached the end of the array.

        return increasing or decreasing