544/670

544. Monotonic Array

Easy

An array is monotonic if it never changes direction: either every step stays the same or goes up (non-decreasing, nums[i] <= nums[i+1] for all valid i), or every step stays the same or goes down (non-increasing, nums[i] >= nums[i+1] for all valid i).

Given an integer array nums, return true if it is monotonic in either direction and false otherwise.

Equal neighbors are allowed in both directions — [3, 3, 3] counts as both non-decreasing and non-increasing.

Example 1:

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

Output: true

Explanation: Every neighboring pair satisfies nums[i] <= nums[i+1], so the array is non-decreasing.

Example 2:

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

Output: true

Explanation: Every neighboring pair satisfies nums[i] >= nums[i+1], so the array is non-increasing.

Example 3:

Input: nums = [1, 3, 2]

Output: false

Explanation: The array rises from 1 to 3 and then falls to 2 — it changes direction, so it is not monotonic.

Constraints:

  • 1 ≤ nums.length ≤ 10⁵
  • -10⁹ ≤ nums[i] ≤ 10⁹

Hints:

The array fails only if it strictly rises somewhere AND strictly falls somewhere else. Equal neighbors never disqualify anything.

Track two booleans in one pass: 'saw an increase' and 'saw a decrease'. The answer is false exactly when both become true.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

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

Expected output: true