AlgorithmsData StructuresContact
Monotonic Array
Rami Del Toro
Rami Del Toro
September 04, 2021
15 min

Table Of Contents

01
Overview
02
Optimal Solution
03
Flow Diagram
04
Time Complexity
05
Space Complexity
06
Java Source Code
07
Conclusion
Monotonic Array

An array is monotonic if it is either monotone increasing or monotone decreasing.

An array nums is monotone increasing if for all i <= j, nums[i] <= nums[j]. An array nums is monotone decreasing if for all i <= j, nums[i] >= nums[j].

Given an integer array nums, return true if the given array is monotonic, or false otherwise.

Overview

Monotonic Array problem description
Monotonic Array examples

Optimal Solution

Monotonic Array optimal solution
Monotonic Array Solution Diagram

Flow Diagram

Monotonic Array flow diagram
Optimal Solution Flow Diagram

Simply checking each element with the previous element and keeping track of the trend, is a perfect and elegant solution.

Time Complexity

As we are traversing the whole array once, the time complexity is O(n). No other complex operation needed.

Space Complexity

No extra space is needed for this algorithm. Space complexity is constant O(1). I like it.

Java Source Code

    public boolean isMonotonic(int[] array) {
        boolean isNonDecresing = true;
        boolean isNonIncreasing = true;

        for(int i=1;i<array.length;i++) {
            if(array[i] < array[i-1]) {
                isNonDecresing = false;
            }

            if(array[i] > array[i-1]) {
                isNonIncreasing = false;
            }
        }

        return isNonDecresing || isNonIncreasing;
    }

Conclusion

The trend is your friend.

Martin Zweig

Tags

algorithmsarrayeasy

Related Posts

How to implement the MergeSort Algorithm
How to implement the MergeSort Algorithm
October 10, 2021
25 min
© 2022 Rami Del Toro ,All Rights Reserved.