medium

Non-decreasing Array

Check if an array can become non-decreasing by changing one element.

1. Define the problem

Non-decreasing Array

Given an array of n integers, decide whether it can become non-decreasing (each element no smaller than the one before it) by modifying at most one element . Scan for the first place order breaks, then check the neighbors to decide which side to fix — a second break means one fix was not enough.

Constraints

  • n == nums.length
  • 1 ≤ n ≤ 104
  • -105 ≤ numsi ≤ 105

Example

Inputnums = [4, 2, 3]
Outputtrue

Explanation Lowering the 4 down to 2 gives [2, 2, 3], which is non-decreasing — so only one modification was needed.

2. Know the words first

In plain terms

Which side to fix
When nums[i-1] > numsi, either lower nums[i-1] down to numsi or raise numsi up to nums[i-1] — whichever keeps the two elements before the break in order too.
3. Visualize the solution

Fix the first break, then check if a second one appears

Fix the first break, then check if a second one appears
Statusviolation

i=1: nums[0]=4 > nums[1]=2 — order is broken.

What happens in this step

i = 1
nums[0] = 4, nums[1] = 2
4 > 2, so this is a violation
Step 1 of 5

Steps to visualize

  1. Walk the array looking for the first place where a value is smaller than the one right before it.
  2. When that happens, decide whether to lower the earlier value or raise the later one — lower the earlier value unless doing so would break the pair before it.
  3. Apply that one fix and keep scanning.
  4. If a second break is found after the first fix, one modification is not enough — the array can never become non-decreasing this way.
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.

Fix the first break, then check if a second one appears
Statusviolation

i=1: nums[0]=4 > nums[1]=2 — order is broken.

What happens in this step

i = 1
nums[0] = 4, nums[1] = 2
4 > 2, so this is a violation
Step 1 of 5
5. Solution

Solution

solution.tsTypeScript
function checkPossibility(nums) {
  let modifications = 0;

  for (let i = 1; i < nums.length; i++) {
    if (nums[i - 1] <= nums[i]) {
      continue;
    }

    modifications++;

    if (modifications > 1) {
      return false;
    }

    if (i < 2 || nums[i - 2] <= nums[i]) {
      nums[i - 1] = nums[i];
    } else {
      nums[i] = nums[i - 1];
    }
  }

  return true;
}
Time
O(n)
Space
O(1)
6. Test cases

Test cases

InputExpectedCovers
nums = [4, 2, 3]trueexample from the docstring
nums = [4, 2, 1]falsetwo separate violations require more than one modification
nums = [1]truesmallest valid input: a single element is trivially non-decreasing
nums = [1, 2, 3, 4]truean already non-decreasing array needs no modification
nums = [1, 4, 2, 3]truea violation where raising the later value is the correct fix
nums = [3, 4, 2, 3]falsea violation where the first fix is not enough to prevent a second one