LeetCode Problem 26 - Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array

Problem

Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.

Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:

int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length

int k = removeDuplicates(nums); // Calls your implementation

assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
    assert nums[i] == expectedNums[i];
}

My Solution

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
        int k = 0;
        unordered_set<int> dupSet;
        for(int i = 0; i< nums.size();i++){
            if(dupSet.find(nums[i]) == dupSet.end()){
                dupSet.insert(nums[i]);
                nums[k++]=nums[i];
            }
        }
        return k;
    }
};

Explanation

This problem is similar to LeetCode Problem 27 - Remove Element except instead of looking for a specific value, we're looking for a duplicate value. To determine if a value is a duplicate, we can use an unordered_set which works by hashing a value. This lets us determine if we've already inserted a value into the map, it will fail, and we can increment the count variable and replace the element at k with i

Proper Solution

class Solution {
public:
    int removeDuplicates(vector<int>& nums) {
       	int k=1;
	    for(int i=1; i<nums.size(); i++){
            if(nums[i]!=nums[i-1]) nums[k++] = nums[i]; 
        }        
		        
	    return k;
    }
};

Explanation

Our version missed a criteria that this problem needed to be solved "in place". We used unordered set to assist which violated the constraints. In this solution k and i begin at one since we know that we don't have an empty set and we don't care what the first element is as it won't be a duplicate. Then, we simply check to see if the value does not equal the previous value and assign as necessary.