29- Monotonic Array
The problem can be found at the following link: Question Link
My Approach
Initialize two boolean flags,
increasinganddecreasing, totrue. These flags will help us track whether the array is non-increasing or non-decreasing, respectively.Iterate through the array
numsstarting from index1(comparing each element with the previous one).For each pair of adjacent elements, check whether
nums[i]is greater thannums[i - 1]. If it is, set the decreasing flag to false because this indicates that the array is not decreasing.If
nums[i]is less thannums[i - 1], set theincreasingflag to false because this indicates that the array is not increasing.Continue this process for the entire array.
After the loop, check whether either
increasingordecreasingistrue. If either of them is true, it means that the array is monotonic (either non-increasing or non-decreasing), so returntrue. Otherwise, returnfalse.
Time and Auxiliary Space Complexity
Time Complexity:
O(n)Auxiliary Space Complexity:
O(1)
Code (C++)
class Solution {
public:
bool isMonotonic(vector<int>& nums) {
bool increasing = true;
bool decreasing = true;
for (int i = 1; i < nums.size(); i++) {
if (nums[i] > nums[i - 1]) {
decreasing = false;
} else if (nums[i] < nums[i - 1]) {
increasing = false;
}
}
return increasing || decreasing;
}
};
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star to the rishabhv12/Daily-Leetcode-Solution repository.
Last updated
Was this helpful?