75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

26. Remove Duplicates from Sorted Array (Easy)

Naive Solution

Code

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        set<int> st;
        for(auto &x: nums) st.insert(x);
        int i=0;
        for(auto &x: st) nums[i++]=x;
        return st.size();
    }
};

2 pointer solution

Code

class Solution {
public:
    int removeDuplicates(vector<int>& nums)
    {
        int n = nums.size(), i = 0;
        if (n == 0) return 0;
        for (int j = 1; j < n; j++) { // notice: loop is for J
            if (nums[i] != nums[j]) nums[++i] = nums[j];
        }
        return i + 1;
    }
};