Check if an array is monotonic.

An array is monotonic is all the elements are either in non-decreasing or in non-increasing order. In other words, for any array arr , its monotonic is arr[i]>=arr[i+1] or arr[i]<=arr[i+1] , for all the elements arr[i] in the array.


Solution 1

Let us devise a strategy where we will find the if the array is in increasing or decreasing order. Following is the code, a very naiive solution:

def isMonotonic(self, nums: List[int]) -> bool: # naiive solution l = len(nums) old_trend = 0 for i in range(1,l): if nums[i]>nums[i-1]: trend = 1 elif nums[i]<nums[i-1]: trend = -1 else: trend = 0 if old_trend==0: old_trend=trend elif trend!=0 and old_trend!=trend: return False elif trend!=0: old_trend = trend continue return True

Idea:


Solution 2

Let us devise a slightly better solution. Here, we will use two boolean variables to track the increasing trend and decreasing trend. Since the output desired is also boolean, any breakage in trend in any of these two variables can be passed as OR operation as output. (We only need one to be True until the end.)

def isMonotonic(self, nums: List[int]) -> bool: trend_p = True trend_n = True l = len(nums) for i in range(l-1): if nums[i]>nums[i+1]: trend_n = False elif nums[i]<nums[i+1]: trend_p = False return trend_n or trend_p