Non Decreasing Array

Decide whether changing at most one number can put an array in non-decreasing order.

Take an array of integers nums. An array is non-decreasing when every number is at least as big as the one before it, so equal neighbours are allowed. Return true if you can make nums non-decreasing by changing at most one of its numbers to any value you like, and false otherwise.

Example 1
Input: nums = [4, 2, 3]
Output: true
Explanation: change 4 to 1, and the array reads [1, 2, 3].
Example 2
Input: nums = [4, 2, 1]
Output: false
Example 3
Input: nums = [3, 4, 2, 3]
Output: false
Explanation: the array goes down only once, from 4 to 2, but no single change fixes it.
Solution

The Idea

Read the numbers from left to right as the steps of a staircase. A non-decreasing array is a staircase that only goes up or stays level. A place where a number is smaller than the one before it, so the staircase goes down, is what we will call a drop.

Example 1, [4, 2, 3], has one drop, from 4 to 2. Change the 4 to any value of 2 or less, such as 1, and the drop is gone. Example 2, [4, 2, 1], has two drops: 4 to 2, and 2 to 1. Changing the middle 2 cannot fix both, because its new value would have to be at least 4 and at most 1.

That holds for any two drops. If they do not share a number, one change cannot reach both of them. So a second drop always means the answer is false. But Example 3, [3, 4, 2, 3], has only one drop, from 4 to 2, and the answer is still false. What goes wrong there?

A drop can be fixed in two ways: make the left number smaller, or make the right number bigger. Look at the picture below.

The array 3, 4, 2, 3 has one drop, between 4 and 2. Lowering 4 to 2 gives 3, 2, 2, 3, with a new drop between 3 and 2. Raising 2 to 4 gives 3, 4, 4, 3, with a new drop between 4 and 3.

The top row is nums, with its drop from 4 to 2 marked in orange. In the middle row, the 4 is lowered to 2. That fixes the marked pair, but the 3 in front of it is now bigger than 2, a new drop on the left. In the bottom row, the 2 is raised to 4 instead. Now the 3 after it is smaller, a new drop on the right. Either way a second change would be needed.

So fixing a drop is really about the numbers around it. Lowering the left number can only clash with the number in front of it. Raising the right number can clash with the numbers after it, which have not been looked at yet. That makes lowering the safer fix: it leaves the right number, and everything after it, as it was. Raising is the way out when lowering would clash.

Solution Approach

Turning that idea into code means settling three things: how to find the drops, which number to change at a drop, and how to make sure the change did not create a new drop.

Finding the drops

Why not try every position as the one to change? For each position you would pick a value and check the whole array again, which takes about n² comparisons for n numbers. One walk from left to right is enough instead. Compare each number with the one before it and count the drops. At the second drop, the answer is false.

Choosing which number to change

Which fix should a drop at position i get? The left number is nums[i - 1] and the right one is nums[i]. Lowering nums[i - 1] to nums[i] works when the number in front of it, nums[i - 2], is not bigger than nums[i]. It also works when i is 1, because then nothing stands in front.

Take [1, 4, 2, 3]. Lowering 4 to 2 gives [1, 2, 2, 3], which is in order. Raising 2 to 4 would give [1, 4, 4, 3], with a new drop from 4 to 3. That is why lowering comes first.

When lowering would clash, raise nums[i] to nums[i - 1]. That is the smallest value that fixes the drop, so it leaves the most room for the numbers after it. In [5, 7, 1, 8], lowering 7 to 1 would put it below 5, so the 1 becomes 7 and the array reads [5, 7, 7, 8].

Checking the changed number

How do we know a raise did not create a new drop on the right? Write the new value into the array. The walk compares nums[i] with the number after it on its next step anyway, so it sees the raised value. In Example 3, the 2 becomes 4, and the next step compares that 4 with 3 and finds the second drop. A lowered number needs no such check, because it is lowered only when nums[i - 2] is not bigger than its new value.

Java Solution

The method checkPossibility works in these steps:

  1. First, set a counter changes to 0. Then loop with i from 1 to the end of the array, comparing nums[i] with nums[i - 1]. If nums[i] is at least as big, there is no drop, and the loop moves on.
  2. At a drop, add 1 to changes. If it is now more than 1, this is the second drop, so return false.
  3. If i is less than 2, or nums[i - 2] is not bigger than nums[i], lower nums[i - 1] to nums[i].
  4. Otherwise, raise nums[i] to nums[i - 1]. The new value stays in the array, so the next round of the loop compares it with the number after it.
  5. When the loop ends with at most one drop fixed, return true.

The main method runs the three examples, then [1, 4, 2, 3] and [5, 7, 1, 8] from above, a drop at the very end, equal numbers, and a single number. For each array it prints the input, the answer and the array after the call.

Java
import java.util.Arrays;

public class NonDecreasingArray {

    public static boolean checkPossibility(int[] nums) {
        int changes = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] >= nums[i - 1]) {
                continue;                     // no drop here
            }
            if (++changes > 1) {
                return false;                 // a second drop needs a second change
            }
            if (i < 2 || nums[i - 2] <= nums[i]) {
                nums[i - 1] = nums[i];        // lower the left value: nothing after it moves
            } else {
                nums[i] = nums[i - 1];        // lowering would break nums[i - 2], so raise
            }
        }
        return true;
    }

    static void check(int... nums) {
        String before = Arrays.toString(nums);
        boolean ok = checkPossibility(nums);
        System.out.println(before + " -> " + ok + ", array now " + Arrays.toString(nums));
    }

    public static void main(String[] args) {
        check(4, 2, 3);
        check(4, 2, 1);
        check(3, 4, 2, 3);
        check(1, 4, 2, 3);
        check(5, 7, 1, 8);
        check(1, 2, 4, 5, 3);
        check(1, 1, 1);
        check(7);
    }
}

Running it prints:

Output
[4, 2, 3] -> true, array now [2, 2, 3]
[4, 2, 1] -> false, array now [2, 2, 1]
[3, 4, 2, 3] -> false, array now [3, 4, 4, 3]
[1, 4, 2, 3] -> true, array now [1, 2, 2, 3]
[5, 7, 1, 8] -> true, array now [5, 7, 7, 8]
[1, 2, 4, 5, 3] -> true, array now [1, 2, 4, 5, 5]
[1, 1, 1] -> true, array now [1, 1, 1]
[7] -> true, array now [7]

Look at the first line: [4, 2, 3] comes back as [2, 2, 3]. The 4 was lowered to 2 inside the caller's own array, so pass a copy if the original is still needed. In the second line, the 4 was lowered too before the drop from 2 to 1 ended the walk.

The third line is Example 3. It ends as [3, 4, 4, 3], the bottom row of the picture: the 2 was raised, and the next comparison found the second drop. Writing the raise into the array is what catches it. A version that only counts drops, without changing anything, returns true for this array, and so does one that always lowers the left number.

The next two lines show each fix on its own: [1, 4, 2, 3] is fixed by lowering the 4, and [5, 7, 1, 8] by raising the 1. In [1, 2, 4, 5, 3] the drop is at the very end, and raising the 3 to 5 fixes it. [1, 1, 1] is true without any change, because equal neighbours are not a drop. For [7] the loop never runs.

The original implementation, NonDecreasingArray.java, is on GitHub.

Complexity

The method walks the array once and keeps only a counter.

  • Time: O(n), for an array of n numbers, because the loop compares each number with the one before it once, makes at most one change, and stops early at a second drop.
  • Space: O(1). The fix is written into nums itself, and only changes and i are added.

Making a choice and writing it into the array, so that later steps see it, also solves Can Place Flowers.