easy

Monotonic Array

Check whether an array is entirely non-increasing or non-decreasing.

1. Define the problem

Monotonic Array

An array is monotonic if it is either entirely non-increasing or entirely non-decreasing. Given an integer array nums, return true if the given array is monotonic, or false otherwise. Make a single pass checking two flags at once: whether any adjacent pair breaks the non-decreasing rule, and whether any adjacent pair breaks the non-increasing rule.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -105 ≤ numsi ≤ 105

Example

Inputnums = [1, 2, 2, 3]
Outputtrue

Explanation Each value is greater than or equal to the one before it, so the array is non-decreasing.

2. Know the words first

In plain terms

Monotonic
Consistently moving in one direction — either every step stays the same or goes up, or every step stays the same or goes down, with no mixing of both.
3. Visualize the solution

Track both increasing and decreasing possibilities at once

Track both increasing and decreasing possibilities at once
Statusinit

Compare nums[0]=1 and nums[1]=2. 1 <= 2, so isIncreasing stays true; 1 < 2 breaks isDecreasing (false).

What happens in this step

nums[0]=1, nums[1]=2
1 <= 2 (isIncreasing stays true)
1 < 2 (isDecreasing becomes false)
Step 1 of 4

Steps to visualize

  1. Start with two flags: isIncreasing = true and isDecreasing = true.
  2. Walk through adjacent pairs of the array.
  3. If a later value is smaller than an earlier one, isIncreasing becomes false.
  4. If a later value is larger than an earlier one, isDecreasing becomes false.
  5. The array is monotonic if isIncreasing or isDecreasing remains true at the end.
4. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Track both increasing and decreasing possibilities at once
Statusinit

Compare nums[0]=1 and nums[1]=2. 1 <= 2, so isIncreasing stays true; 1 < 2 breaks isDecreasing (false).

What happens in this step

nums[0]=1, nums[1]=2
1 <= 2 (isIncreasing stays true)
1 < 2 (isDecreasing becomes false)
Step 1 of 4
5. Solution

Solution

solution.tsTypeScript
function isMonotonic(nums) {
  let isIncreasing = true;
  let isDecreasing = true;

  for (let i = 1; i < nums.length; i++) {
    if (nums[i] < nums[i - 1]) {
      isIncreasing = false;
    }
    if (nums[i] > nums[i - 1]) {
      isDecreasing = false;
    }
  }

  return isIncreasing || isDecreasing;
}
Time
O(n)
Space
O(1)
6. Test cases

Test cases

InputExpectedCovers
nums = [1, 2, 2, 3]trueexample from the docstring
nums = [6, 5, 4, 4]truestrictly non-increasing with a tie
nums = [1, 3, 2]falsearray that goes up then down
nums = [5]truesmallest valid input, a single element is trivially monotonic
nums = [3, 3, 3]trueevery value identical, both increasing and decreasing hold
nums = [5, 4, 3, 2, 1]truestrictly decreasing with no ties