Q#43: Monotonic Array

Can you check if a given array containing n integers is monotonic? Your function should return “true” if it is monotonic and “false” if it’s not.

An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].

For example:

Input : [6, 5, 4, 4]
Output : true
Input : [5, 5, 5, 4]
Output : true
Input : [5, 15, 20, 10]
Output : false

TRY IT YOURSELF

ANSWER

This question tests your Python skills as well as how you problem solve. The task is to build a function that determines whether a series is monotonic, meaning it only increases or only decreases, or not. There are many approaches, but we will showcase one that only iterates through the list once.

Thinking through this problem, an easy solution would be to check the each number in the list is smaller or bigger than the next number in the list. With this in mind, a simple solution is to have two ‘flag’ variables, one for increasing and one for decreasing, and check that only one of the flags is active. To do this in python, we can utilize booleans (True/False) conditions. For the case where the consecutive number is the same, we can just pass over.

def check_monotonic(nums_list) -> bool:   # Keep track of the first number and initialize flags to false
first_num = nums_list[0]
is_pos = is_neg = False
# Iterate over the remaining length of the list, raising flags if next number is greater (is_pos) or lower (is_neg)
for i in range(1,len(l)):
if nums_list[i] > first_num:
is_pos = True
first_num = nums_list[i]
elif nums_list[i] < first_num:
is_neg = True
first_num = nums_list[i]
else:
pass
#If both flags raise we can stop the loop and return False
if is_pos == True and is_neg == True:
return False
# This return only happens if the above loop goes to completion
return True

--

--