DEV Community

Giuseppe
Giuseppe

Posted on

LeetCode #26. Remove duplicates from sorted array

Two pointers solution

Time Complexity: O(n)

  • Single loop through the array from index 1 to n-1
  • Each iteration does constant time operations (comparison, assignment)
  • n elements = n operations = O(n)

Space Complexity: O(1)

  • Array modified in place
  • Space usage does not increase with input size
class Solution { 
   public int removeDuplicates(int[] nums) { 
      if (nums.length == 0) return 0; 

      // already have one unique element 
      int k = 1; 

      // start comparing from the second element 
      for (int i = 1; i < nums.length; i++) { 
         if (nums[i] != nums[k - 1]) { 
            nums[k] = nums[i]; 
         k++; 
      } 
      return k; 
   } 
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)