Problem

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, orfalse otherwise.

Examples

Example 1

1
2
Input: nums = [1,2,2,3]
Output: true

Example 2

1
2
Input: nums = [6,5,4,4]
Output: true

Example 3

1
2
Input: nums = [1,3,2]
Output: false

Constraints

  • 1 <= nums.length <= 10^5
  • -10^5 <= nums[i] <= 10^5

Solution

Method 1 - One Pass Check

Intuition

Check if the array is monotone increasing or monotone decreasing in a single pass.

Approach

Iterate through the array, track if it is increasing or decreasing. If both are false at any point, return false.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    public boolean isMonotonic(int[] nums) {
        boolean inc = true, dec = true;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > nums[i-1]) dec = false;
            if (nums[i] < nums[i-1]) inc = false;
        }
        return inc || dec;
    }
}
1
2
3
4
5
6
7
8
def isMonotonic(nums):
    inc = dec = True
    for i in range(1, len(nums)):
        if nums[i] > nums[i-1]:
            dec = False
        if nums[i] < nums[i-1]:
            inc = False
    return inc or dec

Complexity

  • ⏰ Time complexity: O(n) — One pass through the array.
  • 🧺 Space complexity: O(1) — Only a few variables used.