Skip to content
Related Articles

Related Articles

Python Program to check if given array is Monotonic

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 27 Sep, 2022
Improve Article
Save Article

Given an array A containing n integers. The task is to check whether the array is Monotonic or not. An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i <= j, A[i] <= A[j]

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

Return Type: Boolean value, “True” if the given array A is monotonic else return “False” (without quotes). 

Examples:

Input : 6 5 4 4
Output : true

Input : 5 15 20 10
Output : false

Approach : Using extend() and sort()

  • First copy the given array into two different arrays using extend()
  • Sort the first array in ascending order using sort()
  • Sort the second array in descending order using sort(reverse=True)
  • If the given array is equal to any of the two arrays then the array is monotonic

Python3




# Check if given array is Monotonic
def isMonotonic(A):
    x, y = [], []
    x.extend(A)
    y.extend(A)
    x.sort()
    y.sort(reverse=True)
    if(x == A or y == A):
        return True
    return False
 
 
# Driver program
A = [6, 5, 4, 4]
 
# Print required result
print(isMonotonic(A))


Output

True

Time Complexity: O(N*logN), where N is the length of the array.
Auxiliary space: O(N), extra space is required for lists x and y.

Approach: 

An array is monotonic if and only if it is monotone increasing, or monotone decreasing. Since p <= q and q <= r implies p <= r. So we only need to check adjacent elements to determine if the array is monotone increasing (or decreasing), respectively. We can check each of these properties in one pass.

To check whether an array A is monotone increasing, we’ll check A[i] <= A[i+1] for all i indexing from 0 to len(A)-2. Similarly we can check for monotone decreasing where A[i] >= A[i+1] for all i indexing from 0 to len(A)-2. 

Note: Array with single element can be considered to be both monotonic increasing or decreasing, hence returns “True“. 

Below is the implementation of the above approach: 

Python3




# Python Program to check if given array is Monotonic
 
# Check if given array is Monotonic
 
 
def isMonotonic(A):
 
    return (all(A[i] <= A[i + 1] for i in range(len(A) - 1)) or
            all(A[i] >= A[i + 1] for i in range(len(A) - 1)))
 
 
# Driver program
A = [6, 5, 4, 4]
 
# Print required result
print(isMonotonic(A))
 
# This code is written by
# Sanjit_Prasad


Output

True

Time Complexity: O(N), where N is the length of the array.
Auxiliary space: O(1) because it is using constant space.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!