Problem 211938 · easy · Phase 02 Linear Data Structures

Is It Monotonic?

arrays · iteration · checks

A list is monotonic if it is entirely non-increasing or entirely non-decreasing (equal neighbours are allowed). Return True if nums is monotonic, else False. Lists with fewer than two elements are monotonic.

Examples

Input:  nums = [1, 2, 2, 3]
Output: True

Input:  nums = [6, 5, 4, 4]
Output: True

Input:  nums = [1, 3, 2]
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…