Monotonic Array

Easy · Arrays & Hashing · Array

Problem

An array is monotonic when it never changes direction: it is either entirely non-decreasing (nums[i] = nums[j] whenever i <= j). Equal neighbors are allowed either way.

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

Examples

Input: nums = [9,9,4,1]
Output: true

Every step stays level or goes down, so the array is non-increasing.

Input: nums = [2,5,5,3]
Output: false

The step from 2 to 5 goes up and the step from 5 to 3 goes down: two directions.

Input: nums = [-1]
Output: true

A single value has no steps at all, so it is monotonic.

Constraints

Approaches

Follow-up

What if the array arrives as a stream and you must answer after every new value? The two flags are all the state you need: update them with the newest step and report not (rises and falls). Once both are set the answer is false forever.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…