665 Non-decreasing Array

Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.

We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).

Example 1:

Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Example 2:

Input: [4,2,1]
Output: False
Explanation: You can't get a non-decreasing array by modify at most one element.

Note: The n belongs to [1, 10,000].

The Idea: If the goal is to produce an increasing sequence, then we know that if we want two or more numbers in the array that make it a decreasing sequence, there is no way to remedy it, so we can return false. This implies that the first value that causes a decreasing sequences determines entirely whether it is possible. Intuitively if we remove (ignore) any one of these two elements and if in either case, we obtain an increasing sequence then we know it was possible to modify one value to do so. Rather than deleting the elements in the array, what we do is modify one to mirror the other in two seperate arrays. This has the effect of creating an >= case and hence ignoring the value when we sort.

Complexity: O(nlogn) time and O(2n) space

def checkPossibility(self, nums):
    """
    :type nums: List[int]
    :rtype: bool
    """

    one = nums[:]
    two = nums[:]
    for i in range(1, len(nums)):
        if (nums[i-1] > nums[i]):
            one[i-1] = nums[i]
            two[i] = nums[i-1]
            return sorted(one) == one or sorted(two) == two
    return True

Last updated