Python Program to check if given array is Monotonic (original) (raw)
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 #include #include
using namespace std;
// Function to check if given array is monotonic bool isMonotonic(vector& A) { vector x = A; vector 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 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
`
Output
True 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)