Skip to main content
  1. Problem Solving Solutions/

Remove Duplicates from Sorted Array II LeetCode Solution

·1 min
leetcode
Mayukh Datta
Author
Mayukh Datta
Table of Contents

This is a bit tricky problem. The easier variant of this problem is here.

Problem: https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

Solution in C++ #

class Solution { public: int removeDuplicates(vector& a) {

    int n = a.size();
    
    if(n <= 1) {
        return n;
    }
    
    int i = 0, j = 0;
    while(j < n) {
        // keep at most two duplicates
        // and skip the others
        while(j < n-2 && a\[j\] == a\[j+2\]) {
            j++;
        }
        
        cout << a\[i\] << a\[j\] << endl; //stdout
        a\[i\] = a\[j\];
        i++;
        j++;
    }
    
    return i;
}

};

Alternate C++ Solution #

class Solution { public: int removeDuplicates(vector& a) {

    int n = a.size();
    
    if(n <= 2) {
        return n;
    }
    
    // using two pointers and a counter approach
    
    int i = 0, j, count = 0;
    
    for(j=0; j<n; j++){
        
        if(j == 0 || a\[j\] == a\[j-1\]) {
            count++;
        }else{
            count = 1;
        }
        
        // if count is 1 or 2
        if(count < 3) {
            a\[i++\] = a\[j\];
        }
    }
    
    return i;
}

};