NeetCode #64LC-896EasyArrays & Hashing
← Back to All Problems

#64 · #896 · Monotonic Array(单调数列)

📌 Problem Statement & Constraints

An array is monotonic if it is either non-increasing or non-decreasing. Given an integer array nums, return true if it is monotonic. Constraints: 1 <= nums.length <= 10^5, -10^5 <= nums[i] <= 10^5.

💡 Core Algorithmic Approaches

  1. Track two booleans: whether the array has so far been non-decreasing and whether it has been non-increasing.
  2. For each adjacent pair, clear inc if nums[i] > nums[i + 1], and clear dec if nums[i] < nums[i + 1].
  3. The array is monotonic if either flag survives the whole scan.
  4. Equal pairs clear neither flag, which correctly allows arrays with plateaus such as [1, 1, 2].

💻 Benchmark Python3 Implementation

class Solution:
    def isMonotonic(self, nums: List[int]) -> bool:
        inc = dec = True
        for i in range(len(nums) - 1):
            if nums[i] > nums[i + 1]:
                inc = False
            if nums[i] < nums[i + 1]:
                dec = False
        return inc or dec

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass.
💾 Space Complexity
O(1): two booleans.

⚠️ Interview Pitfalls & Follow-ups

  • Using inc &= nums[i] <= nums[i+1] with short-circuit expectations: this actually works in Python, but the two separate if statements are clearer and avoid confusion with bitwise operators on booleans.
  • Clearing both flags on an equal pair: equality is compatible with both monotonic directions.
  • Returning as soon as one flag clears: the other direction may still hold, so you must finish the scan.
  • Requiring strict monotonicity: the statement allows equal neighbours.