Given a sorted array, remove duplicates in place so each unique value appears once, and return the count of unique values — the first part of the array up to that count holds the result.
Video coming soon
We're producing a video walkthrough — check back soon.
Given a sorted array, remove duplicates in place so each unique value appears once, and return the count of unique values — the first part of the array up to that count holds the result.
Builds directly on the write-pointer idea from Move Zeroes, but now the decision to advance depends on comparing against the previous kept value rather than checking for a fixed sentinel like 0 — a pattern that reappears constantly once arrays are sorted.
Whenever an array is described as already sorted and the task is to compact it down to only the values that satisfy some 'different from the last kept one' rule, a write pointer that compares against its own most recently written value is enough — no extra memory needed.
Since the array is sorted, every run of duplicate values is contiguous, so a value only needs to be compared against the most recently kept value — never the whole prefix. Keep a write pointer `i` starting at 0 (the first element is always kept). Scan the array with a read pointer `j` from index 1: whenever nums[j] differs from nums[i], it's a new unique value, so increment `i` first and then copy nums[j] into nums[i]. Once the scan finishes, the first i + 1 slots of the array hold the unique values in order, so the length to return is i + 1.
class Solution {
public 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;
}
}