Remove Duplicates from Sorted Array II

Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element can appear atmost twice and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

Note that even though we want you to return the new length, make sure to change the original array as well in place

For example, Given input array A = [1,1,1,2],

Your function should return length = 3, and A is now [1,1,2].

public class Solution {
    public int removeDuplicates(ArrayList<Integer> nums) {
        boolean second = false;
        int i = 0;
        for (int j = 1; j < nums.size(); j++) {
            if (nums.get(i).compareTo(nums.get(j)) == 0) {
                if (!second) {
                    i++;
                    nums.set(i, nums.get(j));
                    second = true;
                }
            } else {
                second = false;
                i++;
                nums.set(i, nums.get(j));
            }
        }
        while (nums.size() > (i + 1))
            nums.remove(nums.size() - 1);
        return i + 1;
    }
}

Last updated