Python Program to check if given array is Monotonic
Last Updated :
22 Apr, 2024
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
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Function to check if given array is monotonic
bool isMonotonic(vector<int>& A) {
vector<int> x = A;
vector<int> y = A;
sort(x.begin(), x.end());
sort(y.rbegin(), y.rend());
if (x == A || y == A) {
return true;
}
return false;
}
// Driver program
int main() {
vector<int> A = {6, 5, 4, 4};
// Print required result
cout << boolalpha << isMonotonic(A) << endl;
return 0;
}
Java
import java.util.Arrays;
public class Main {
// Function to check if the given array is monotonic
public static boolean isMonotonic(int[] A) {
int[] x = new int[A.length];
int[] y = new int[A.length];
// Copy elements of A to arrays x and y
System.arraycopy(A, 0, x, 0, A.length);
System.arraycopy(A, 0, y, 0, A.length);
// Sort arrays x and y
Arrays.sort(x);
Arrays.sort(y);
reverse(y);
// Check if A is equal to either x or y
return Arrays.equals(x, A) || Arrays.equals(y, A);
}
// Function to reverse the array
public static void reverse(int[] arr) {
int start = 0;
int end = arr.length - 1;
while (start < end) {
// Swap elements at start and end indices
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
// Move indices towards the middle
start++;
end--;
}
}
// Driver program
public static void main(String[] args) {
int[] A = {6, 5, 4, 4};
// Print the result
System.out.println(isMonotonic(A));
}
}
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))
JavaScript
// Function to check if given array is monotonic
function isMonotonic(A) {
const x = [...A];
const y = [...A];
x.sort((a, b) => a - b);
y.sort((a, b) => b - a);
return JSON.stringify(x) === JSON.stringify(A) || JSON.stringify(y) === JSON.stringify(A);
}
// Driver program
function main() {
const A = [6, 5, 4, 4];
// Print required result
console.log(isMonotonic(A));
}
// Calling main function
main();
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))
Time Complexity: O(N), where N is the length of the array.
Auxiliary space: O(1) because it is using constant space.
Approach 3 - By checking length of the array
Python3
def isMonotonic(arr):
if len(arr) <= 2:
return True
direction = arr[1] - arr[0]
for i in range(2, len(arr)):
if direction == 0:
direction = arr[i] - arr[i - 1]
continue
if (direction > 0 and arr[i] < arr[i - 1]) or (direction < 0 and arr[i] > arr[i - 1]):
return False
return True
# Example usage
arr1 = [1, 2, 3, 4, 5] # True
arr2 = [5, 4, 3, 2, 1] # True
arr3 = [1, 2, 2, 3, 4] # True
arr4 = [1, 2, 3, 4, 5, 4] # False
print(isMonotonic(arr1)) # should return True
print(isMonotonic(arr2)) # should return True
print(isMonotonic(arr3)) # should return True
print(isMonotonic(arr4)) # should return False
OutputTrue
True
True
False
This program first checks if the length of the array is less than or equal to 2, in which case it returns True. Next, it initializes a variable "direction" to the difference between the first two elements of the array. Then, it iterates through the rest of the array and checks if the current element is greater than or less than the previous element, depending on the direction. If any element does not match the direction, the function returns False. If the function completes the loop and has not returned False, it returns True.
Please note that this program assumes that the input array is a list of integers, if the input array consists of other data types it will not work as expected.
The time complexity of the above program is O(n). This is because the program iterates through the entire array once, and the amount of time it takes to complete the iteration is directly proportional to the number of elements in the array. The program uses a single variable "direction" to store the difference between the first two elements of the array, and a single variable "i" to keep track of the current index during iteration.
The auxiliary space of the above program is O(1). This is because the program only uses a constant amount of extra memory to store the single variable "direction" and the single variable "i". The program does not create any new data structures or use any recursion, so it does not require any additional memory beyond the input array.
Approach : By using the set to Identify Unique Elements
In this we will check, if the array is monotonic by converting it to a set to identify unique elements and then determining monotonicity by comparing the array against both its ascending and descending sorted versions. If either comparison holds true, the array is considered monotonic.
Below is implementation for the above approach:
Python3
def is_monotonic(arr):
unique_elements = set(arr)
increasing = sorted(arr) == arr or sorted(arr, reverse=True) == arr
return increasing
# Driver Code
arr1 = [6, 5, 4, 4]
arr2 = [5, 15, 20, 10]
arr3 = [2, 2, 2, 3]
print(is_monotonic(arr1))
print(is_monotonic(arr2))
print(is_monotonic(arr3))
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach : By using all and any Functions
In this approach, we are using all() function to check if the given array is monotonic or not.
Python3
def is_monotonic(arr):
increasing = all(arr[i] <= arr[i + 1] for i in range(len(arr) - 1))
decreasing = all(arr[i] >= arr[i + 1] for i in range(len(arr) - 1))
return increasing or decreasing
# Example
input_array1 = [6, 5, 4, 4]
input_array2 = [5, 15, 20, 10]
result1 = is_monotonic(input_array1)
result2 = is_monotonic(input_array2)
print(result1)
print(result2)
Time complexity : O(n)
Auxiliary Space : O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem