int[] nums = {1,1,2,2,3,4,4,5}; int k = removeDuplicates(nums); System.out.print("Length: " + k + ", Array: "); for (int i = 0; i < k; i++) { System.out.print(nums[i] + " "); } public static int removeDuplicates(int[] nums) { if (nums.length == 0) return 0; int i = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j]; } } return i + 1; }
The two-pointer method moves unique elements to the front. The variable i tracks the last unique element's index. When a new unique element is found at j, it is placed at i+1. The final length is i + 1.
The two-pointer approach scans the array once and moves unique elements forward in-place, so it uses O(1) extra space and O(n) time.
public static int removeDuplicates(int[] nums) { int i = 0; for (int j = 1; j <= nums.length; j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j]; } } return i + 1; }
The loop uses j <= nums.length, which causes nums[j] to access an index equal to the array length, causing an ArrayIndexOutOfBoundsException.
int[] nums = {0,0,1,1,1,2,2,3,3,4}; int k = removeDuplicates(nums); System.out.print("Length: " + k + ", Array: "); for (int i = 0; i < k; i++) { System.out.print(nums[i] + " "); } public static int removeDuplicates(int[] nums) { if (nums.length == 0) return 0; int i = 0; for (int j = 1; j < nums.length; j++) { if (nums[j] != nums[i]) { i++; nums[i] = nums[j]; } } return i + 1; }
The unique numbers are 0,1,2,3,4. The method moves them to the front and returns length 5.
The two-pointer method modifies the array in-place, uses constant extra space, and keeps the original order of elements, which is efficient and desirable.
