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.
1def isMonotonic(nums):
2 increasing = True
3 decreasing = True
4 for i in range(1, len(nums)):
5 if nums[i] > nums[i - 1]:
6 decreasing = False
7 if nums[i] < nums[i - 1]:
8 increasing = False
9 return increasing or decreasing
Using Python, we initialize two boolean flags set to True. As we iterate through the list, we update these flags similarly based on the comparison of adjacent elements. The function returns True if the array is either entirely non-decreasing or non-increasing.
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.
1using namespace std;
bool isIncreasing(const vector<int>& nums) {
for (int i = 1; i < nums.size(); i++) {
if (nums[i] < nums[i - 1]) return false;
}
return true;
}
bool isDecreasing(const vector<int>& nums) {
for (int i = 1; i < nums.size(); i++) {
if (nums[i] > nums[i - 1]) return false;
}
return true;
}
bool isMonotonic(vector<int>& nums) {
return isIncreasing(nums) || isDecreasing(nums);
}
C++ implementation uses two distinct functions to check for increasing and decreasing constraints. Each function scans through the vector independently, confirming monotonicity in either direction.