29- Monotonic Array
The problem can be found at the following link: Question Link
My Approach
Initialize two boolean flags,
increasing
anddecreasing
, totrue
. These flags will help us track whether the array is non-increasing or non-decreasing, respectively.Iterate through the array
nums
starting 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 theincreasing
flag to false because this indicates that the array is not increasing.Continue this process for the entire array.
After the loop, check whether either
increasing
ordecreasing
istrue
. 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++)
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