Python Program to check if given array is Monotonic
In this tutorial, we will learn how to check if an array is monotone or not. An array is a container data structure that stores elements, where each element can be accessed by an index. An array is said to be monotonic in nature if the array elements are continuously increasing or continuously decreasing.
Monotonic increasing
An array A[] is monotonic increasing if all the elements in it satisfy the condition
for all i <= j, A[i] <= A[j]
[1, 2, 3, 4, 7, 10] is monotonic increasing.
Monotonic decreasing
An array A[] is monotone decreasing if all the elements in it satisfy the condition:
for all i <= j, A[i] >= A[j]
[11, 10, 9, 6, 4, 1] is monotonic decreasing.
The program should take the array as input and return True if the array is monotonic else it should return False. For example,
Look at the sample input and output for the program.
Input: 7 3 2 1 0
Output: True
Input: 10 11 13 9 14
Output: False
We will follow the approach of checking if the array is monotonic increasing or decreasing by checking the adjacent elements in the array. To check for monotonic increasing, we will check if a[i]<= a[i+1] for all indexes i from 0 to n-1 where n is the size of the array. To check for monotonic decreasing, we will check if a[i]>= a[i+1] for all indexes i from 0 to n-1 where n is the size of the array.
An array with only a single element will be treated as a monotone and the function should return the value True in our program.
Algorithm
Look at the algorithm to understand the working of the program.
Step 1- Define a function that will check the monotone nature of the array
Step 2- Find and store size of array using len()
Step 3- If the array has only one element return True
Step 4- Else, check if all values in the array are continuously decreasing or continuously increasing
Step 5- If the condition is true, return True
Step 6- If the condition is not true, return False
Step 7- Declare an array with values
Step 8- Pass the array in the function
Step 9- Print the result
Python Program
This is the program to check if an array is monotone or not. We have defined a function which will return True if the array is monotone else it will return False.
#check if monotone
#function definition
def ismonotone(a):
n=len(a) #size of array
if n==1:
return True
else:
#check for monotone behaviour
if all(a[i]>=a[i+1] for i in range(0,n-1) or a[i]<=a[i+1] for i in range(0,n-1)):
return True
else:
return False
A = [6, 5, 4, 2]
print(ismonotone(A))
b = [6, 2, 4, 2]
print(ismonotone(b))
c=[4,3,2]
print(ismonotone(c))
d=[1]
print(ismonotone(d))
True
False
True
True
Conclusion
In this tutorial, we have learned about what are monotone arrays and how can we check if an array is a monotone or not using a function. There are two types of monotonic arrays- monotone increasing and monotone decreasing. If an array has only 1 element then it is monotone.