Check if given Array is Monotonic
Last Updated :
10 Apr, 2023
Given an array arr[] containing N integers, the task is to check whether the array is monotonic or not (monotonic means either the array is in increasing order or in decreasing order).
Examples:
Input: arr[] = {1, 2, 2, 3}
Output: Yes
Explanation: Here 1 < 2 <= 2 < 3.
The array is in increasing order. Therefore it is monotonic.
Input: arr[] = {6, 5, 4, 3}
Output: Yes
Explanation: Here 6 > 5 > 4 > 3.
The array is in decreasing order. So it is monotonic.
Input: arr[] = {1, 5, 2}
Output: No
Explanation: Here 1 < 5 > 2. The array is neither increasing nor decreasing.
So the array is not monotonic
Approach: The problem can be solved by checking if the array is in increasing order or in decreasing order. This can be easily done in the following way:
- If for each i in range [0, N-2], arr[i] ≥ arr[i+1] the array is in decreasing order.
- If for each i in range [0, N-2], arr[i] ≤ arr[i+1], the array is in increasing order.
Follow the below steps to solve the problem:
- Traverse the array arr[] from i = 0 to N-2 and check if the array is increasing in order
- Traverse the array arr[] from i = 0 to N-2 and check if the array is decreasing in order
- If neither of the above two is true, then the array is not monotonic.
Below is the implementation of the above approach:
C++
// C++ program for above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check array is monotonic
bool check(vector<int>& arr)
{
int N = arr.size();
bool inc = true;
bool dec = true;
// Loop to check if array is increasing
for (int i = 0; i < N - 1; i++) {
// To check if
// array is not increasing
if (arr[i] > arr[i + 1]) {
inc = false;
}
}
// Loop to check if array is decreasing
for (int i = 0; i < N - 1; i++) {
// To check if
// array is not decreasing
if (arr[i] < arr[i + 1]) {
dec = false;
}
}
// Pick one whether inc or dec
return inc || dec;
}
// Driver code
int main()
{
vector<int> arr = { 1, 2, 3, 3 };
// Function call
bool ans = check(arr);
if (ans)
cout << "Yes";
else
cout << "No";
return 0;
}
Java
// Java program for above approach
import java.io.*;
class GFG {
// Function to check array is monotonic
static boolean check(int arr[])
{
int N = arr.length;
boolean inc = true;
boolean dec = true;
// Loop to check if array is increasing
for (int i = 0; i < N - 1; i++) {
// To check if
// array is not increasing
if (arr[i] > arr[i + 1]) {
inc = false;
}
}
// Loop to check if array is decreasing
for (int i = 0; i < N - 1; i++) {
// To check if
// array is not decreasing
if (arr[i] < arr[i + 1]) {
dec = false;
}
}
// Pick one whether inc or dec
return inc || dec;
}
// Driver code
public static void main (String[] args) {
int arr[] = { 1, 2, 3, 3 };
// Function call
boolean ans = check(arr);
if (ans == true)
System.out.print("Yes");
else
System.out.print("No");
}
}
// This code is contributed by hrithikgarg03188.
Python3
# Python program for above approach
# Function to check array is monotonic
def check(arr):
N = len(arr)
inc = True
dec = True
# Loop to check if array is increasing
for i in range(0, N-1):
# To check if array is not increasing
if arr[i] > arr[i+1]:
inc = False
# Loop to check if array is decreasing
for i in range(0, N-1):
# To check if array is not decreasing
if arr[i] < arr[i+1]:
dec = False
# Pick one whether inc or dec
return inc or dec
# Driver code
if __name__ == "__main__":
arr = [1, 2, 3, 3]
# Function call
ans = check(arr)
if ans == True:
print("Yes")
else:
print("No")
# This code is contributed by Rohit Pradhan
C#
// C# program for above approach
using System;
class GFG {
// Function to check array is monotonic
static bool check(int[] arr)
{
int N = arr.Length;
bool inc = true;
bool dec = true;
// Loop to check if array is increasing
for (int i = 0; i < N - 1; i++) {
// To check if
// array is not increasing
if (arr[i] > arr[i + 1]) {
inc = false;
}
}
// Loop to check if array is decreasing
for (int i = 0; i < N - 1; i++) {
// To check if
// array is not decreasing
if (arr[i] < arr[i + 1]) {
dec = false;
}
}
// Pick one whether inc or dec
return (inc || dec);
}
// Driver code
public static void Main()
{
int[] arr = { 1, 2, 3, 3 };
// Function call
bool ans = check(arr);
if (ans)
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>
// JavaScript program for above approach
// Function to check array is monotonic
const check = (arr) => {
let N = arr.length;
let inc = true;
let dec = true;
// Loop to check if array is increasing
for (let i = 0; i < N - 1; i++) {
// To check if
// array is not increasing
if (arr[i] > arr[i + 1]) {
inc = false;
}
}
// Loop to check if array is decreasing
for (let i = 0; i < N - 1; i++) {
// To check if
// array is not decreasing
if (arr[i] < arr[i + 1]) {
dec = false;
}
}
// Pick one whether inc or dec
return inc || dec;
}
// Driver code
let arr = [1, 2, 3, 3];
// Function call
let ans = check(arr);
if (ans)
document.write("Yes");
else
document.write("No");
// This code is contributed by rakeshsahni
</script>
Time Complexity: O(N)
Auxiliary Space: O(1)
Another Approach: (JavaScript) In this approach JavaScript's array method, named as every() will be used and therefore we will further check using this method that the array passed is Monotonic in nature or not.
Follow the below mentioned steps:
- Traverse the array using every() method and check whether the current element is smaller than previous element.
- Similarly again using every() method as well as with the usage of Logical OR Operator ( | | ) check whether the current element is greater than the previous element or not.
- Return true if either of the increasing sequence or the decreasing sequence is found out.
Below is the implementation of the above approach:
C++
// c++ code
#include <iostream>
#include <algorithm>
using namespace std;
// Function to check monotonic sequence
bool check_monotonic(int array[], int size)
{
// First check for decreasing order sequence...
if (is_sorted(array, array + size, greater<int>()))
return true;
// Then check for increasing order sequence...
if (is_sorted(array, array + size))
return true;
// Not Monotonic
return false;
}
// Driver Code
int main()
{
int array1[] = { 7, 5, 3, 1 };
int array2[] = { 4, 0, 3, 1 };
int array3[] = { 5, 4, 3 };
int size1 = sizeof(array1) / sizeof(array1[0]);
int size2 = sizeof(array2) / sizeof(array2[0]);
int size3 = sizeof(array3) / sizeof(array3[0]);
if (check_monotonic(array1, size1))
cout << "Is Monotonic ?: true\n";
else
cout << "Is Monotonic ?: false\n";
if (check_monotonic(array2, size2))
cout << "Is Monotonic ?: true\n";
else
cout << "Is Monotonic ?: false\n";
if (check_monotonic(array3, size3))
cout << "Is Monotonic ?: true\n";
else
cout << "Is Monotonic ?: false\n";
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
public class GFG {
// Function to check monotonic sequence
static boolean checkMonotonic(int[] array) {
int size = array.length;
// First check for decreasing order sequence...
if (isSorted(array, size, true))
return true;
// Then check for increasing order sequence...
if (isSorted(array, size, false))
return true;
// Not Monotonic
return false;
}
// Function to check if an array is sorted in either ascending or descending order
static boolean isSorted(int[] array, int size, boolean isDescending) {
if (isDescending) {
for (int i = 1; i < size; i++) {
if (array[i] > array[i - 1])
return false;
}
} else {
for (int i = 1; i < size; i++) {
if (array[i] < array[i - 1])
return false;
}
}
return true;
}
// Driver Code
public static void main(String[] args) {
int[] array1 = {7, 5, 3, 1};
int[] array2 = {4, 0, 3, 1};
int[] array3 = {5, 4, 3};
if (checkMonotonic(array1))
System.out.println("Is Monotonic ?: true");
else
System.out.println("Is Monotonic ?: false");
if (checkMonotonic(array2))
System.out.println("Is Monotonic ?: true");
else
System.out.println("Is Monotonic ?: false");
if (checkMonotonic(array3))
System.out.println("Is Monotonic ?: true");
else
System.out.println("Is Monotonic ?: false");
}
}
Python3
def check_monotonic(array):
return (
# First check for decreasing order sequence...
all(element <= array[index - 1] for index, element in enumerate(array) if index > 0) or
# Then check for increasing order sequence...
all(element >= array[index - 1] for index, element in enumerate(array) if index > 0)
)
print("Is Monotonic ?: ", check_monotonic([7, 5, 3, 1]))
print("Is Monotonic ?: ", check_monotonic([4, 0, 3, 1]))
print("Is Monotonic ?: ", check_monotonic([5, 4, 3]))
JavaScript
let checkMonotonic = (array) => {
return (
// First check for decreasing order sequence...
array.every(
(element, index) => index === 0 || element <= array[index - 1]
) ||
// Then check for increasing order sequence...
array.every((element, index) => index === 0 || element >= array[index - 1])
);
};
console.log("Is Monotonic ?: " + checkMonotonic([7, 5, 3, 1]));
console.log("Is Monotonic ?: " + checkMonotonic([4, 0, 3, 1]));
console.log("Is Monotonic ?: " + checkMonotonic([5, 4, 3]));
// This code is contributed by Aman Singla...
C#
using System;
using System.Linq;
class Gfg {
static void Main() {
int[] array1 = { 7, 5, 3, 1 };
int[] array2 = { 4, 0, 3, 1 };
int[] array3 = { 5, 4, 3 };
Console.WriteLine("Is Monotonic ?: " + checkMonotonic(array1));
Console.WriteLine("Is Monotonic ?: " + checkMonotonic(array2));
Console.WriteLine("Is Monotonic ?: " + checkMonotonic(array3));
}
static bool checkMonotonic(int[] array) {
return (
// First check for decreasing order sequence...
array.Take(1).Count() == array.Length ||
Enumerable.Range(1, array.Length - 1).All(i => array[i] <= array[i - 1])
||
// Then check for increasing order sequence...
Enumerable.Range(1, array.Length - 1).All(i => array[i] >= array[i - 1])
);
}
}
OutputIs Monotonic ?: true
Is Monotonic ?: false
Is Monotonic ?: true
Time Complexity: O(NlogN), as the time complexity of the is_sorted() function in the standard library is O(NlogN), where N is the size of the array.
Auxiliary Space: O(1), as it requires constant extra space for storing the size of the array.
Similar Reads
Check if a given array is pairwise sorted or not
An array is considered pairwise sorted if each successive pair of numbers is in sorted (non-decreasing) order. In case of odd elements, last element is ignored and result is based on remaining even number of elements. Examples: Input : arr[] = {10, 15, 9, 9, 1, 5}; Output : Yes Pairs are (10, 15), (
5 min read
Check for Mountain Array
Given an array arr[]. The task is to check whether it is a mountain array or not. A mountain array is an array of length at least 3 with elements strictly increasing from starting till an index i, and then strictly decreasing from index i to last index. More formally arr[0] < arr[1] < arr[i]
5 min read
Check if an Array is Sorted
Given an array of size n, the task is to check if it is sorted in ascending order or not. Equal values are allowed in an array and two consecutive equal values are considered sorted.Examples: Input: arr[] = [20, 21, 45, 89, 89, 90]Output: YesInput: arr[] = [20, 20, 45, 89, 89, 90]Output: YesInput: a
9 min read
Check if a given array is sorted in Spiral manner or not
Given an array arr[] of size N, the task is to check if the array is spirally sorted or not. If found to be true, then print "YES". Otherwise, print "NO". Note: An array is spirally sorted if arr[0] ? arr[N - 1] ? arr[1] ? arr[N - 2] ... Examples: Input: arr[] = { 1, 10, 14, 20, 18, 12, 5 } Output:
5 min read
Check whether the given array is perfect or not
There is an array containing some non-negative integers. Check whether the array is perfect or not. An array is called perfect if it is first strictly increasing, then constant and finally strictly decreasing. Any of the three parts can be empty. Examples: Input : arr[] = {1, 8, 8, 8, 3, 2}Output :
5 min read
Check if all possible Triplet Sum is present in given Array
Given an array arr[] of size N, the task is to check if for all distinct triplets of indices i, j, k, [ 0 ⤠i < j < k ⤠N-1 ] the sum arr[i]+arr[j]+arr[k] is present in the array. Examples: Input: arr[] = {-1, 0, 0, 1}Output: TrueExplanation: For index 0, 1, 2: arr[i]+arr[j]+arr[k] = -1 + 0 +
9 min read
Check if the array is beautiful
Given an integer n and an array of size n check if it satisfies following conditions:- All elements of array must lie between 1 to n.Array must NOT be sorted in ascending order.The array consists of unique elements.If all conditions satisfied print Yes else No. Examples: Input: 4 1 2 3 4Output: NoAr
9 min read
Check if given array is almost sorted (elements are at-most one position away)
Given an array with n distinct elements. An array is said to be almost sorted (non-decreasing) if any of its elements can occur at a maximum of 1 distance away from their original places in the sorted array. We need to find whether the given array is almost sorted or not.Examples: Input : arr[] = {1
11 min read
Check if Array Elemnts can be Made Equal with Given Operations
Given an array arr[] consisting of N integers and following are the three operations that can be performed using any external number X. Add X to an array element once.Subtract X from an array element once.Perform no operation on the array element.Note : Only one operation can be performed on a numbe
6 min read
Check whether a given array is a k sorted array or not
Given an array of n distinct elements. Check whether the given array is a k sorted array or not. A k sorted array is an array where each element is at most k distances away from its target position in the sorted array. For example, let us consider k is 2, an element at index 7 in the sorted array, c
12 min read