Sponsored
Sponsored
This approach involves traversing the array and maintaining two flags: one for checking if the array elements are in increasing order and another for checking if they are in decreasing order. As we iterate through the array, we update these flags accordingly. If the array violates both conditions at any point, it is not monotonic.
Time Complexity: O(n), where n is the length of the array, since we perform a single traversal of the array.
Space Complexity: O(1), as no extra space is utilized apart from the flags.
1function isMonotonic(nums) {
2 let increasing = true, decreasing = true;
3 for (let i = 1; i < nums.length; i++) {
4 if (nums[i] > nums[i - 1])
5 decreasing = false;
6 if (nums[i] < nums[i - 1])
7 increasing = false;
8 }
9 return increasing || decreasing;
10}
In JavaScript, we use let to define the flags for increasing and decreasing. A loop through the array determines if the sequence is non-decreasing or non-increasing, setting the respective flags. The function yields true if the sequence holds for one side.
In this approach, we perform two separate passes to test for monotonic increase and monotonic decrease independently. The first pass checks for strictly increasing nature, and the second checks for strictly decreasing nature.
Time Complexity: O(n), two passes over the array which are separate checks.
Space Complexity: O(1), with no additional space used beyond flags.
1
The C solution uses two helper functions, isIncreasing
and isDecreasing
, which independently check if the array is monotone increasing or decreasing. The main function returns true if either condition holds true.