Look only after trying hard! C++ soln


#1
int Solution::removeDuplicates(vector<int> &A) {
    // Do not write main() function.
    // Do not read input, instead use the arguments to the function.
    // Do not print the output, instead return values as specified
    // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details

    // problem statement not very clearly written. It should be mentioned for numbers having duplicates greater or equal to 2 should appear exactly twice
    // and for unique numbers only once. Instead its written at most twice that means all unique elements should pass the tests but they don't.

    // anyways it is an easy problem. using a flag to note a repeatition solves the problem.
    // we set the flag for every new element and once the element is added twice (for duplicates) we set the flag back to false not adding further duplicates.
    if(A.size() == 1) return 1;
    int ptr = 0, i;
    bool flag = true;
    for(i=0;i<A.size() - 1;i++)
    {
        if(A[i] != A[i + 1])
        {
            A[ptr ++] = A[i];
            flag = true;
        }
        else if(A[i] == A[i + 1] && flag)
        {
            A[ptr++] = A[i];
            flag = false;
        }
    }
    A[ptr++] = A[A.size() - 1];
    return ptr;

}