I coded an algorithm to determine if an input array is a monotonic array (its elements from left to right are entirely increasing or entirely decreasing) or not.
I was wondering what the space complexity of this algorithm is. I am thinking it is O(n) because the count increases as the size of the array increases. Basically I am increasing the count every time the current element is <= or >= to the next element. So the largest value of count and count2 would basically be the size of the input array if the loop goes through every element.
Could someone please explain and correct me if I am wrong?
def monotonic(array):
count = 0
count2 = 0
for i in range(len(array) - 1):
if array[i] <= array[i + 1]:
count += 1
if array[i] >= array[i + 1]:
count2 += 1
if array == []: return True
if count == len(array) - 1 or count2 == len(array) - 1:
return True
else:
return False