Non Decreasing Array
We define an array is non-decreasing if nums[i] <= nums[i + 1]i0 <= i <= n - 2
Example 1
Output: true
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2
Output: false
Explanation: You cannot get a non-decreasing array by modifying at most one element.
Constraints:
n == nums.length1 <= n <= 104-105 <= nums[i] <= 105
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. nums[i] <= nums[i+1]truefalse
But there is one use case, when we detect an element at index ii+1i-1th
Say if the input array is [2, 4, 3][2, 3, 4][2, 4, 3, 3][2, 4, 4, 3][2, 3, 3, 3]
Let's another example, say if the input array is [3, 4, 1][3, 1, 1][3, 4, 4]
Implementation details:
-
Initialize a
flagboolean to track if a array is modified once, set the intial value to bemodified .false -
Next, loop through array elements from index
toi = 0 of the input array and if the number at indexi = n-1 is greater than the element ati index, do the following:i+1-
First, check
flag, if this ismodified , that means array is already modified once, so returntrue , otherwise continue to next step.false -
If the next element to current element, that is
element is greater than previous elementi+1th element, then copyi-1th element toi+1th , by doing so, these 3 positions will satisfy the conditioni .nums[i-1] <= nums[i] <= nums[i+1] -
Otherwise, copy copy
indxed element toith index to satisfy the condition satisfy the conditioni+1 .nums[i-1] <= nums[i] <= nums[i+1] -
If the array is modified once, set the
flag tomodified .true
-
First, check
public class NonDecreasingArray {
static boolean checkPossibility(int[] nums) {
boolean modified = false;
for(int i=0; i<nums.length-1; i++) {
if (nums[i] > nums[i + 1]) {
if (modified) {
return false;
}
if (i == 0 || nums[i + 1] >= nums[i - 1]) { // i==0 if there are only two elements in array
nums[i] = nums[i + 1];
} else {
nums[i + 1] = nums[i];
}
modified = true;
}
}
return true;
}
public static void main(String[] args) {
System.out.println(checkPossibility(new int[]{4,2,3}));
System.out.println(checkPossibility(new int[]{-1,4,2,3}));
System.out.println(checkPossibility(new int[]{4,2,1}));
}
}
Complexity Analysis:
Time complexity: Above code runs in O(n) time where nnums
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