Non-decreasing Array (LeetCode 665): Solution and Explanation

Medium
Array

Scan once, count drops where nums[i] < nums[i - 1], and repair each drop greedily: lower nums[i - 1] when nums[i - 2] <= nums[i], otherwise raise nums[i]. A second drop means the answer is false.

Intuition

Draw the array as bars. A non-decreasing array is a staircase that never steps down, so every place where a bar is shorter than its left neighbour is a problem spot.

Each drop needs at least one change, so two drops already mean false. With one drop the question is which of the two bars to change.

Lowering the left bar nums[i - 1] down to nums[i] is the better move because it keeps the values small for everything that comes later. It only works if the bar before it, nums[i - 2], is not taller than nums[i]. If it is, the only option is to raise nums[i] up to nums[i - 1], and that higher value must be written back so the next comparison sees it.

Approach: Greedy single repair

  1. Set fixes = 0 and walk i from 1 to n - 1.
  2. If nums[i] >= nums[i - 1], continue.
  3. Otherwise increase fixes. If fixes is now 2, return false.
  4. If i < 2 or nums[i - 2] <= nums[i], set nums[i - 1] = nums[i]; otherwise set nums[i] = nums[i - 1].
  5. Return true after the loop.

Step-by-step example

nums = [4,2,3]
  1. Start with fixes = 0.
  2. i = 1: 2 < 4 is a drop, so fixes = 1. There is no nums[i - 2], so lower nums[0] to 2. The array is now [2,2,3].
  3. i = 2: 3 >= 2, nothing to do.
  4. The loop ends with only one repair, so the answer is true.

Code: Python, Java, C++

1class Solution:
2    def checkPossibility(self, nums: List[int]) -> bool:
3        fixes = 0
4        for i in range(1, len(nums)):
5            if nums[i] >= nums[i - 1]:
6                continue
7            fixes += 1
8            if fixes > 1:
9                return False
10            if i < 2 or nums[i - 2] <= nums[i]:
11                nums[i - 1] = nums[i]
12            else:
13                nums[i] = nums[i - 1]
14        return True
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Each index is compared with its left neighbour once, and each repair is O(1).

Space

O(1)

Only the repair counter is stored; the array is fixed in place.

Other approaches

Try both repairs and check (time O(n), space O(n))

Find the first drop, then build two copies of the array, one with nums[i - 1] lowered and one with nums[i] raised, and check whether either copy is sorted. It is easy to reason about but scans the array three times and copies it.

Brute force (time O(n^2), space O(1))

For each index, replace it with a value that could fit and check whether the array is non-decreasing. Correct but quadratic.

Common mistakes

  • Only counting drops. [3,4,2,3] has a single drop but no single change fixes it, because 2 is below both 3 and 4.
  • Always lowering nums[i - 1]. When nums[i - 2] > nums[i], lowering creates a new drop on the left.
  • Raising nums[i] without writing it back. The next comparison must see the raised value, or a later drop is missed.

Frequently asked questions

Why prefer lowering nums[i - 1] over raising nums[i]?

Every value after index i has to be at least nums[i]. Keeping nums[i] at its original, smaller value gives the rest of the array the most room, so lowering the left bar never hurts when it is legal.

Is it fine to modify the input array?

Yes for this problem. The change is what makes the next comparisons correct. If you must keep the input intact, track the effective previous value in a variable instead.

What does nums[i - 2] have to do with it?

After lowering nums[i - 1] to nums[i], the pair (nums[i - 2], nums[i - 1]) must still be in order. That holds exactly when nums[i - 2] <= nums[i].