An array is monotonic if it is entirely non-decreasing or entirely non-increasing. We can check each condition separately. First, scan to see if every element is greater than or equal to the previous one. If this holds, the array is monotonically increasing. If not, scan again to check if every element is less than or equal to the previous one. If either condition is satisfied, the array is monotonic.
nums[i] < nums[i - 1] for any i. If found, the array is not increasing.true.nums[i] > nums[i - 1] for any i. If found, the array is not decreasing.class Solution:
def isMonotonic(self, nums: List[int]) -> bool:
n = len(nums)
increase = True
for i in range(1, n):
if nums[i] < nums[i - 1]:
increase = False
break
if increase:
return True
decrease = True
for i in range(1, n):
if nums[i] > nums[i - 1]:
decrease = False
break
return decreaseWe can determine the expected direction by comparing the first and last elements. If the first element is less than or equal to the last, the array should be non-decreasing. Otherwise, it should be non-increasing. With the direction determined upfront, a single pass can verify whether all consecutive pairs follow the expected pattern.
nums[0] and nums[n - 1] to determine the expected direction.nums[0] <= nums[n - 1], the array should be non-decreasing:false if any nums[i] < nums[i - 1].false if any nums[i] > nums[i - 1].true.Rather than deciding the direction upfront, we can track both possibilities simultaneously. We maintain two flags: one for whether the array could still be non-decreasing, and one for whether it could still be non-increasing. As we scan, any violation disqualifies that direction. At the end, if at least one flag remains true, the array is monotonic.
increase = true and decrease = true.(nums[i], nums[i + 1]):nums[i] > nums[i + 1], set increase = false.nums[i] < nums[i + 1], set decrease = false.increase || decrease.A monotonic array allows equal consecutive elements (non-decreasing or non-increasing). Using strict comparisons like nums[i] > nums[i-1] instead of nums[i] >= nums[i-1] incorrectly rejects arrays like [1, 2, 2, 3] as non-monotonic. The condition should check for <= (non-decreasing) or >= (non-increasing) to properly handle equal adjacent values.
Arrays that are constant (all elements equal) are both non-decreasing and non-increasing. Returning false early when detecting a violation in one direction without checking the other leads to incorrect results. The array [5, 5, 5] should return true, but checking only for strictly increasing or strictly decreasing patterns would fail this case.