Monotonic Array

An array is monotonic if it is either monotone increasing (nums[i] <= nums[j] for all i <= j) or monotone decreasing (nums[i] >= nums[j] for all i <= j). Given an integer array nums, return true if it is monotonic, or false otherwise.

30:00

Monotonic Array
easy
Free written solution
Topics
Companies

An array is monotonic if it is either monotone increasing (nums[i] <= nums[j] for all i <= j) or monotone decreasing (nums[i] >= nums[j] for all i <= j). Given an integer array nums, return true if it is monotonic, or false otherwise.

Example 1:
Input: {"nums":[1,2,2,3]}
Output: true
Constraints:
  • 1≤nums.length≤1051 \leq \text{nums.length} \leq 10^5

  • −105≤nums[i]≤105-10^5 \leq \text{nums}[i] \leq 10^5

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,2,3]}

Keep two candidate shapes alive: "never goes down" and "never goes up". Each step between neighbours can rule one of them out.

increasing = true

no step down yet

decreasing = true

no step up yet

the array as a path: each step is up, down or flat

1223

up: kills decreasing

down: kills increasing

flat: harmless

steps checked

1
·
2
·
2
·
3
Variables
VariableValue
increasingtrue
decreasingtrue
DepthFunction Call
Stack empty
0/5