Skip to main content

Monotonic Array

Problem Description​

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.

Example​

Example 1:

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

Example 2:

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

Constraints​

  • -10^5 <= nums[i] <= 10^5

Solution Approach​

Intuition:​

To efficiently determine the monotonic array

Solution Implementation​

Code In Different Languages:​

Written by @Ishitamukherjee2004
 
class Solution {
isMonotonic(nums) {
const n = nums.length;
let increasing = true;
let decreasing = true;
for(let i = 0; i < n - 1; i++){
if(nums[i] > nums[i+1]) increasing = false;
if(nums[i] < nums[i+1]) decreasing = false;
}
return increasing || decreasing;
}
}


Complexity Analysis​

  • Time Complexity: O(n)O(n)
  • Space Complexity: O(1)O(1)
  • The time complexity is O(n)O(n) where n is the length of the input array nums. This is because the algorithm iterates through the array once, performing a constant amount of work for each element.
  • The space complexity is O(1)O(1) because we are not using any extra space.