Skip to main content

Non-decreasing Array - LeetCode






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].

Source:LeetCode

At first glance, it looks like an easy and straightforward problem, but believe me it's greedy problem. In the problem, you are allowed to make atmost "one" modification to make a non-decreasing array. Nondecreasing means that every element is greater than or equal to the one before it e.g. [1,3,4,4,5,6,9]. For example, [2,2,3,2,4] can this become non-decreasing? Yes, by replacing 3 with 2 =>[2,2,2,2,4].
What about this: [1,1,1,1,2,1,1]?
Yes, replace "2" with "1" gives [1,1,1,1,1,1,1]

Algorithm

So when nums[i]>nums[i+1] for i>0 ( since we can modify first element to any smallest value to make the sequence non-decreasing we don't need to make any changes, we do increment count (cnt)) if the value before i'th element nums[i-1] is lesser or equals to nums[i+1] we assign nums[i] to nums[i-1] to balance the sequence. 
For example,
arr1 = [1,1,1,1,2,1,1]  => arr1 = [1,1,1,1,1,1,1]
2>1 and 1<=1. "1" is a correct possible modification 

arr2 =[-1,4,2,3]  => arr2 =[-1,-1,2,3]
4>2 and -1<=2. "-1" is a correct possible modification 

In  all other cases, such as [3,4,2,3] 4>2 but 3 is not less than or equal to 2 so the appropriate change here is to replace "3" with a larger value "4" that gives [3,4,4,3] still 4>3 so this array is not non-decreasing array. For simplicity, I choose to modify the value of element with previous element so I don't have to pick any value that will make the array non-decreasing. At last, if count remains less than or equal to one means we have only done one or no modification in the array and return the result.


Java Solution:

 public boolean checkPossibility(int[] nums) {

    int l = nums.length, cnt = 0;

        for (int i = 0; i < l - 1 && cnt <= 1; ++i) {
            if (nums[i] > nums[i + 1]) { // e.g. [2,2,3,2,4] 3>2
                if (i > 0) {
                    if (nums[i - 1] <= nums[i + 1]) // if number is lesser or equal modify nums[i]
                        nums[i] = nums[i - 1];   // to the previous number. 2<=2 modify nums[i] =2
                    else                          // in all other cases modify the next number
                        nums[i + 1] = nums[i]; // to the current number to match// the sequence
                }
                ++cnt;
            }
        }
        return cnt <= 1;
    }

Comments

Post a Comment

Popular posts from this blog

Binary Tree Paths

Source: LeetCode Solution: We do a preorder traversal add each node in the string followed by an arrow "->" if the current node is a leaf node (have no right or left child) then we add the string to the list, otherwise, we add an arrow and make a recursive call in a preorder fashion. The previous string is stored in stack and we can use it later when the call is returned to add another possible routes from root to the leaf nodes.  Complexity Analysis Time complexity : O ( n ) . n nodes need to be traversed ( n represents the number of nodes in a given tree) .   Solution: public List< String > binaryTreePaths( TreeNode root) { ArrayList< String > path = new ArrayList (); binaryPath(root, "" ,path); return path; } public static void binaryPath( TreeNode root, String s, List< String > path){ if (root == null ) return ; ...

Invert Binary Search Tree

Invert a binary tree. Example: 4 / \ 2 7 / \ / \ 1 3 6 9   to   4 / \ 7 2 / \ / \ 9 6 3 1  4 / \ 2 7 / \ / \ 1 3 6 9   Trees are crucial data structure in Computer Science. Often trees related problems are solved using recursion as it provides an elegant solution in this particular problem at least. The basic terminology to solve this problem is to swap the left and right values, if you work on the tree from the bottom the to the top swapping the left and right node, the tree will be inverted. Let's go through an example: You can start from left or right. So, starting from the left we have   2 2 (swap the left and right node) / \ => / \ 1 3 3 1   7 7 (similarly, on the right sub-tree) / \ => / \ 6 9 9 6    Which gives,   4 / \ 2 7 / \ / \ ...