Pages

Wednesday, December 17, 2025

remove duplicates from sorted array - two pointer approach (leetcode)

 class Solution {

    public int removeDuplicates(int[] nums) {
        // base case: return if array have no el.
        if(nums.length == 0) return 0;

        int k = 1; // writer pointer , index = 0 is unique already, so start at 1

        // i - reader pointer
        for(int i=1; i<nums.length; i++) {
            //LOGIC: check if curr. no. is diff than prev. no.
            if(nums[i] != nums[i-1]) {
                // diff? -> unique no. -> store
                nums[k] = nums[i];

                // same? -> not unique. -> dont do anything
                // keep incrementing k
                k++;
               
            }
        }
        return k;
    }
}

remove duplicates from sorted array - two pointer approach (leetcode)

  class Solution {     public int removeDuplicates ( int [] nums ) {         // base case: return if array have no el.         if ( nums...