Monotonic Array

Easy

Topics
Array

An array is monotonic if it is entirely non-increasing or entirely non-decreasing. Given nums, return true if it is monotonic.

Example 1

10212233
The values never change direction, so the array is monotonic and the answer is true.
Cells are the array values; the small numbers underneath are indices.
Input:  nums = [1,2,2,3]
Output: true

Example 2

60514243
Input:  nums = [6,5,4,4]
Output: true

Example 3

103122
The shaded pair reverses direction relative to earlier pairs, so the array is neither non-increasing nor non-decreasing and the answer is false.
Input:  nums = [1,3,2]
Output: false

Constraints

  • 1 <= nums.length <= 10^5
  • -10^5 <= nums[i] <= 10^5
Editorial — intuition, approach, complexity and pitfalls

Intuition

An array is monotonic if it never both rises and falls. Rather than first deciding which direction it is and then checking, assume it might be either and let the data eliminate possibilities: keep two flags, and clear increasing on any descent, decreasing on any ascent. If either flag survives, the array is monotonic.

This handles equal neighbours for free — they violate neither direction and clear nothing — and it needs no special case for which direction the array turns out to be.

Approach

  1. increasing = decreasing = true.
  2. For each adjacent pair, clear the flag the pair contradicts.
  3. Return increasing or decreasing.

Dry Run

nums = [1,2,2,3]
 (1,2) rises -> decreasing = false
 (2,2) equal -> clears nothing
 (2,3) rises -> decreasing = false
 increasing still true -> true

nums = [1,3,2]
 (1,3) rises -> decreasing = false
 (3,2) falls -> increasing = false
 both false -> false

nums = [5,5,5]  nothing cleared, both true -> true

Complexity

  • Time — O(n): one pass. Can exit early once both flags are false, which does not change the bound.
  • Space — O(1): two booleans.

Common Pitfalls

  • Deciding the direction from the first pair. The first pair may be equal, which tells you nothing, and an ad-hoc "skip until they differ" is more code than the two flags.
  • Using strict comparisons for both flags in a way that makes equal neighbours clear both. Equal must clear neither — note the two separate if statements rather than an if/else.
  • Returning increasing and decreasing. That is true only for a constant array.
  • Treating a single-element or empty array as not monotonic. Both are, vacuously, and the loop handles them by never running.

Full Solution — all languages

class Solution:
    def isMonotonic(self, nums):
        inc = dec = True
        for i in range(1, len(nums)):
            if nums[i] > nums[i-1]:
                dec = False
            if nums[i] < nums[i-1]:
                inc = False
        return inc or dec
Asked at Capital One
SensAI
Beta
Tap the mic to stop voice mode