We define an array is non-decreasing if
Output: true
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Output: false
Explanation: You cannot get a non-decreasing array by modifying at most one element.
Constraints:
n == nums.length 1 <= n <= 104 -105 <= nums[i] <= 105
Contents
Solution 1 - Compare previous and next elements and track modified count
In this approach, we are going to compare current element with next element and if they are not in increasing order, i.e.
But there is one use case, when we detect an element at index
Say if the input array is
Let's another example, say if the input array is
Implementation details:
-
Initialize a
boolean flagmodified to track if a array is modified once, set the intial value to befalse . -
Next, loop through array elements from index
i = 0 toi = n-1 of the input array and if the number at indexi is greater than the element ati+1 index, do the following:-
First, check
modified flag, if this istrue , that means array is already modified once, so returnfalse , otherwise continue to next step. -
If the next element to current element, that is
i+1th element is greater than previous elementi-1th element, then copyi+1th element toi , by doing so, these 3 positions will satisfy the conditionnums[i-1] <= nums[i] <= nums[i+1] . -
Otherwise, copy copy
ith indxed element toi+1 index to satisfy the condition satisfy the conditionnums[i-1] <= nums[i] <= nums[i+1] . -
If the array is modified once, set the
modified flag totrue .
-
First, check
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1), since we are using a boolean flag to track if array is modified once.
Above implementations source code can be found at