monotonic array

🏠

Interesting leetcode problem, and a lot harder than it may seem at first. Here's my slightly improved version of the official answer.

 1 class Dir:
 2     inc = 1
 3     flat = 0
 4     dec = -1
 5 
 6 
 7 def isMonotonic(A):
 8     store = Dir.flat
 9     cmp = lambda x, y: Dir.dec if x < y else (Dir.flat if x == y else Dir.inc)
10     for i in range(len(A) - 1):
11         d = cmp(A[i], A[i + 1])
12         if d in [Dir.inc, Dir.dec]:
13             store_initialized = store != 0
14             if store_initialized and d != store:
15                 return False
16             store = d
17     return True
18 
19 
20 assert isMonotonic([0, 0, 0, 0, 0])
21 assert isMonotonic([0, 0, 0, 0, 1])
22 assert isMonotonic([0, 0, 0, 1, 2])
23 assert isMonotonic([-1, 0, 0, 1, 2])
24 
25 assert isMonotonic([-1, -2, 0, 1, 2]) == False
26 
27 assert isMonotonic([*reversed([0, 0, 0, 0, 0])])
28 assert isMonotonic([*reversed([0, 0, 0, 0, 1])])
29 assert isMonotonic([*reversed([0, 0, 0, 1, 2])])
30 assert isMonotonic([*reversed([-1, 0, 0, 1, 2])])

This is quite a difficult problem since when deltas remain flat, the array remains monotonic. This makes it difficult to ascertain the direction (increasing or decreasing).

This serves as a good reminder about cmp, which was actually deprecated in python 3.

1 cmp = lambda x, y: -1 if x < y else (0 if x == y else 1)

cmp offers richer information when comparing two values. In this case, it helps us ignore deltas that are neither go up or down.