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 <vector>
2using namespace std;
3
4bool isMonotonic(vector<int>& nums) {
5 bool increasing = true, decreasing = true;
6 for (int i = 1; i < nums.size(); i++) {
7 if (nums[i] > nums[i - 1])
8 decreasing = false;
9 if (nums[i] < nums[i - 1])
10 increasing = false;
11 }
12 return increasing || decreasing;
13}
Like the C solution, we maintain two flags to check for increasing and decreasing sequences. We iterate through the vector, and based on the comparison of current and previous elements, we update the flags. Finally, we return true if at least one flag remains true.
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.