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.
1class Solution {
2 public boolean isMonotonic(int[] nums) {
3 boolean increasing = true, decreasing = true;
4 for (int i = 1; i < nums.length; i++) {
5 if (nums[i] > nums[i - 1])
6 decreasing = false;
7 if (nums[i] < nums[i - 1])
8 increasing = false;
9 }
10 return increasing || decreasing;
11 }
12}
In Java, we iterate over the array once, updating two flags to track monotonic increase or decrease based on pairwise element comparison. The return value is true if either flag indicates the array is monotonic.
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
In Python, the monotonic nature of the array is verified through two helper functions called by the main function. These functions assume responsibility for taking separate passes through the list, ensuring an accurate determination of monotonicity.