Back to Blog
November 7, 20251 min read

Day #5/50 of Learning DSA

#DSA#dsawithbimlesh#General Programming#remove duplicates in an array

Day #5/50 of Learning DSA

Today marks the fifth day of my 50-day journey into mastering Data Structures and Algorithms (DSA). While I focused on solving the "Remove Duplicates from Sorted Array" problem, I also dedicated time to revisiting essential programming concepts, particularly around functions. This blend of problem-solving and revision is helping me solidify my understanding and build a strong foundation in DSA. Join me as I delve into today's learning experiences and insights.

Remove Duplicates from Sorted Array:

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.

Consider the number of unique elements in nums to be k​​​​​​​​​​​​​​. After removing duplicates, return the number of unique elements k.

The first k elements of nums should contain the unique numbers in sorted order. The remaining elements beyond index k - 1 can be ignored.

Approach (Optimal):

  • Traverse the array using a tracker read and keep comparing it with write tracker.

  • write keep the track of location of last unique element and read iterates throughout the array.

  • This two pointer approach is highly suitable for such type of questions.

    int removeDuplicates(vector<int>& nums) {
        int write = 0;
        int read = 1;

        while(read < nums.size()){
            if(nums[write]!=nums[read]){
                nums[write+1]=nums[read];
                write++;
            }
            read++;
        }
        return write+1;
    }

Read Next