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.
1#include <stdbool.h>
2
3bool isMonotonic(int* nums, int numsSize) {
4 bool increasing = true, decreasing = true;
5 for (int i = 1; i < numsSize; i++) {
6 if (nums[i] > nums[i - 1])
7 decreasing = false;
8 if (nums[i] < nums[i - 1])
9 increasing = false;
10 }
11 return increasing || decreasing;
12}
We loop through the array, starting from the second element. We check if the current element is greater than or less than the previous element and update the respective flags (decreasing and increasing). If both conditions are violated for any element pair, the function returns false. At the end of the loop, if either flag remains true, it implies 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
The JavaScript function segregates the logic for checking monotonic increase and decrease into separate procedures. With complete and individual scans, it evaluates the overall monotonicity of the input array.