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:
- The goal is to find the trend in the array. We do this in a variable trend . The value of +1 indicates increasing trend, -1 indicates decreasing trend and 0 indicates current value is equal to the last value.
- As an initial condition, we set the old_trend value to 0, indicating its neither increasing or decreasing.
- For every next number encountered in the array, we update the trend value.
- If trend is non-zero, and the value is different from old_trend , the monotonicity is broken, so we return False
- Keep on iterating through all the elements of the array.
- If the trend is not broken, the array is monotonic, so we return True
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