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
nums = [4, 2, 3]trueExplanation Lowering the 4 down to 2 gives [2, 2, 3], which is non-decreasing — so only one modification was needed.
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.
Fix the first break, then check if a second one appears
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
Steps to visualize
- Walk the array looking for the first place where a value is smaller than the one right before it.
- 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.
- Apply that one fix and keep scanning.
- If a second break is found after the first fix, one modification is not enough — the array can never become non-decreasing this way.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
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
Solution
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)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [4, 2, 3] | true | example from the docstring |
nums = [4, 2, 1] | false | two separate violations require more than one modification |
nums = [1] | true | smallest valid input: a single element is trivially non-decreasing |
nums = [1, 2, 3, 4] | true | an already non-decreasing array needs no modification |
nums = [1, 4, 2, 3] | true | a violation where raising the later value is the correct fix |
nums = [3, 4, 2, 3] | false | a violation where the first fix is not enough to prevent a second one |