Remove Duplicates from Sorted Array
Problem
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. Return the number of unique elements k; the first k elements of nums must hold the unique elements in order.
Examples
Example 1
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: First two elements become the unique values 1 and 2.
Example 2
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: 5 unique elements written to the front.
Constraints
- •
1 <= nums.length <= 3 * 10^4 - •
-100 <= nums[i] <= 100 - •
nums is sorted in non-decreasing order
Hints
Hint 1
This is a two-pointer problem where both pointers move through the same array, not toward each other.
Hint 2
One pointer (slow) marks where the next unique value should be written; another (fast) scans ahead looking for it.
Hint 3
Because the array is sorted, duplicates are always adjacent — you never need to look further than the last written value.
Solutions
public int removeDuplicatesBruteForce(int[] nums) {
Set<Integer> unique = new LinkedHashSet<>(); // preserves insertion order, which matches sorted order here
for (int n : nums) unique.add(n);
int i = 0;
for (int n : unique) nums[i++] = n;
return unique.size();
}Time: O(n) · Space: O(n) for the Set