[
array
]
Leetcode 0896 Monotonic Array
Problem statement
https://leetcode.com/problems/monotonic-array/
Solution
Just check what is asked in O(n) time and O(1) space. We can do two passes or one pass and do early stopping if needed.
Complexity
Time is O(n), space is O(1).
Code
class Solution:
def isMonotonic(self, A):
inc = dec = True
for i in range(len(A) - 1):
#if not inc and not dec: return False
if A[i] > A[i+1]: inc = False
if A[i] < A[i+1]: dec = False
return inc or dec