Problem 211938 · easy · Level 02 Linear Data Structures

Only Uphill or Only Downhill

arrays · iteration · checks

A cyclist notes the height of the road every hundred metres in nums. The route is monotonic when it never goes up anywhere, or never goes down anywhere; flat stretches (equal neighbours) are fine in either case. Return True for a monotonic route and False for one that climbs somewhere and also drops somewhere. A route with fewer than two readings counts as monotonic.

Examples

Input:  nums = [2, 4, 4, 9]
Output: True

Input:  nums = [8, 8, 5, 1]
Output: True

Input:  nums = [3, 7, 5]
Output: False

Constraints

  • 0 <= len(nums) <= 10**5
  • Target: O(n) time, O(1) extra space, one pass.

Goals

  • Track two boolean facts in a single pass
  • Treat equal neighbours as allowed in both directions
Starting Python…