Remove Duplicates from Sorted Array II in C++


Suppose we have a sorted array nums, we have to remove the duplicates in-place such that duplicates elements will appear at most twice and return the new length. To do this task we cannot take extra space. We have to solve this with O(1) amount of space. For example, if the array is like [0,0,0,1,1,1,1,2,3,3], then the output will be [0,0,1,1,2,3,3], its length is 7

Let us see the steps −

  • len := 2 and n := size of array
  • if n <= 2, then return n
  • for i := 2 to n
    • if nums[i] != nums[len - 2] or nums[i] != nums[len - 1]
      • nums[len] := nums[i], and increase len by 1
  • return len

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int removeDuplicates(vector<int>& nums) {
      int len = 2;
      int n = nums.size();
      if(n <= 2)return n;
      for(int i = 2; i < n; i++){
         if( nums[i] != nums[len - 2] || nums[i] != nums[len - 1]){
            nums[len] = nums[i];
            len++;
         }
      }
      return len;
   }
};
main(){
   Solution ob;
   vector<int> v = {0,0,0,1,1,1,1,2,3,3};
   cout << ob.removeDuplicates(v);
}

Input

[0,0,0,1,1,1,1,2,3,3]

Output

7

Updated on: 04-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements