Remove Duplicates from Sorted Array leetcode

Hii guys, today we are going to solve "Remove duplicates from sorted array" question from LeetCode. The question states that:

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.

Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements.

Return k after placing the final result in the first k slots of nums.

The tricky part is that we have to do it in O(1) space i.e we cannot use any extra array.

For example: Input: nums = [1,1,2] Output: 2, nums = [1,2,_]

The judge is not concerned about what comes after the second element since we will return the number of unique elements, that is, 2.

Input: nums = [0,0,1,1,1,2,2,3,3,4] Output: 5, nums = [0,1,2,3,4,,,,,_] Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. It does not matter what you leave beyond the returned k (hence they are underscores).

Solution

The solution is pretty simple. We will maintain a pointer "i" which will start from 0. Then, we will run a loop from 1 to array's length with the help of pointer "j". Every time we encounter an element which is not equal to array[i] we will replace the element at i+1 position with the element at j position.

int removeDuplicates(vector<int>& nums) {
        int n = nums.size();
      if(n==0){
        return 0;
      }
      int i = 0;
      for(int j=1; j<n; j++){
        if(nums[i]!=nums[j]){
          i++;
          nums[i] = nums[j];
        }

      }
      return i+1;
    }

Hope you got the solution. If you have any question or a better approach then please please please feel free to drop them in the comment box below. Byee.