Remove duplicates allowing each unique element appears at most twice

By   Tewodros   Date Posted: Oct. 13, 2023  Hits: 402   Category:  Algorithm   Total Comment: 0             A+ A-


side

Remove some duplicates in-place from a sorted list of numbers in such a way that each unique element appears at most twice. The relative order of the elements should be kept the same.

 Input: nums = [0,1,1,1,1,2,3,3] 

Output: 6, nums = [0,1,1,2,3,3,_,_] 

Solution:

To solve this problem, we can maintain two pointers: one to iterate through the array (i) and another (j) to mark the position where we should insert the next valid number. Initially, j will point to the third position (index 2), since we know the first two elements are already valid.

While iterating with i, we will compare the current element with the element at position j-2 (two positions behind j). If they're different, it means we can safely insert the current element at position j, then we can increment both pointers. If they're the same, it means we've already inserted this number twice, and we simply move on.

public int RemoveDuplicates(int[] nums) {

      if (nums.Length <= 2) 

      return nums.Length;
 

    int j = 2; 

    for (int i = 2; i < nums.Length; i++) {

        if (nums[i] != nums[j - 2]) {

            nums[j] = nums[i];

            j++;

        }

    }

    return j;

    }


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* ydhsrx

Back to Top