Mental Model
Use two pointers to keep track of unique elements and overwrite duplicates in place.
Analogy: Imagine sorting your bookshelf and moving only unique books forward, skipping duplicates as you go.
[1, 1, 2, 3, 3, 4, 5] ↑ ↑ left right
[1, 1, 2, 3, 3, 4, 5] ↑ ↑ left right
[1, 1, 2, 3, 3, 4, 5] ↑ ↑
[1, 1, 2, 3, 3, 4, 5] ↑ ↑
[1, 2, 2, 3, 3, 4, 5]
↑ ↑[1, 2, 2, 3, 3, 4, 5]
↑ ↑[1, 2, 3, 3, 3, 4, 5]
↑ ↑[1, 2, 3, 3, 3, 4, 5]
↑ ↑[1, 2, 3, 4, 3, 4, 5]
↑ ↑[1, 2, 3, 4, 5, 4, 5]
↑ ↑[1, 2, 3, 4, 5, 4, 5] Unique length = 5
public class RemoveDuplicates { public static int removeDuplicates(int[] nums) { if (nums.length == 0) return 0; int left = 0; for (int right = 1; right < nums.length; right++) { if (nums[right] != nums[left]) { left++; nums[left] = nums[right]; } } return left + 1; } public static void main(String[] args) { int[] nums = {1, 1, 2, 3, 3, 4, 5}; int length = removeDuplicates(nums); for (int i = 0; i < length; i++) { System.out.print(nums[i]); if (i < length - 1) System.out.print(" -> "); } System.out.println(" -> null"); System.out.println("Unique length = " + length); } }
if (nums.length == 0) return 0;int left = 0;for (int right = 1; right < nums.length; right++) {if (nums[right] != nums[left]) {left++;nums[left] = nums[right];return left + 1;if (nums.length == 0) return 0;
if (nums[right] != nums[left]) {if (nums[right] != nums[left]) {Remove Duplicates from Sorted Array problem?i and j for the problem in Java?i starts at 0 to track unique elements, j starts at 1 to scan ahead.i = 0 and j = 1 allows scanning from second element while i marks last unique.[1, 1, 2, 2, 3]?int i = 0, j = 1;
while (j < nums.length) {
if (nums[i] != nums[j]) {
i++;
nums[i] = nums[j];
}
j++;
}
return i;i tracks last unique index, so length is i + 1.i misses counting the first element, causing length off by one.nums = [0,0,1,1,1,2,2,3,3,4], what will be the array state after applying the two-pointer method to remove duplicates?Pass the test and this pattern moves unknown