Given an array A
of integers, return true
if and only if the array is monotonic.
An array is monotonic if it is either monotone increasing or monotone decreasing.
A
is monotone increasing if for all i <= j
, A[i] <= A[j]
.A
is monotone decreasing if for all i <= j
, A[i] >= A[j]
.true
.We need to check if the given array is either monotone increasing or monotone decreasing. We can do this in one pass by maintaining two flags increasing
and decreasing
. We will iterate through the array:
increasing
and decreasing
to true
.A[i] < A[i-1]
, set increasing
to false
.A[i] > A[i-1]
, set decreasing
to false
.increasing
or decreasing
is still true
, then the array is monotonic.#include <vector>
using namespace std;
class Solution {
public:
bool isMonotonic(vector<int>& A) {
if (A.empty()) return true;
bool increasing = true;
bool decreasing = true;
for (int i = 1; i < A.size(); ++i) {
if (A[i] > A[i - 1])
decreasing = false;
if (A[i] < A[i - 1])
increasing = false;
}
return increasing || decreasing;
}
};
The time complexity of this solution is (O(n)), where (n) is the number of elements in the array. This is because we only need to make a single pass through the array to determine if it is monotonic.
The space complexity is (O(1)) because we are using only a constant amount of extra space.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?