Remove Duplicates from Sorted Array

by Utkarsh Jaiswal

Technology

November 16, 2023

|

6 min read

blog image

This problem involves working with an array that is sorted in non-decreasing order. The task is to eliminate duplicate elements in-place, ensuring that each distinct element appears only once. It is crucial to maintain the original order of the elements. The goal is to return the count of unique elements in the array.


Example 1:

Input: nums = [1,1,2]

Output: 2, nums = [1,2,_]

Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.

It does not matter what you leave beyond the returned k (hence they are underscores).


Two-Pointer Approach


We start by setting the unique index to 0, taking advantage of the array being stored in non-decreasing sorted order. The algorithm modifies the input array directly and provides the length of the array containing unique elements as its output. Employing a two-pointer approach, the uniqueIndex variable keeps tabs on the latest index of the unique element discovered thus far. The algorithm iterates through the array, and upon encountering a non-duplicate element, it adjusts the uniqueIndex and updates the array in place.


class Solution {
public:
    int removeDuplicates(vector<int>& nums) {

       if (nums.empty()) {
        return 0;
       }

    int uniqueIndex = 0;
    for (int i = 1; i < nums.size(); i++) {
        if (nums[i] != nums[uniqueIndex]) {
            // If the current element is not a duplicate
            uniqueIndex++;
            nums[uniqueIndex] = nums[i];
        }
    }

    return uniqueIndex + 1;
    }

};


Time Complexity: O(N). Where is the size of array. 

Auxiliary Space: O(1)