Skip to content
Related Articles

Related Articles

Check if given Array is Monotonic

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 17 Jul, 2022
View Discussion
Improve Article
Save Article

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>


Output

Yes

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:

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...


Output:

Is Monotonic ?: true
Is Monotonic ?: false
Is Monotonic ?: true

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!