Remove Duplicates from Sorted Array
In Remove Duplicates from Sorted Array, you are given an array that is already sorted. Your job is to keep only one copy of each distinct value at the front of the array and return how many unique values remain.
The important advantage is that the array is sorted. Because equal values appear next to each other, you do not need a hash set or nested loops to detect duplicates. You only need to notice when the current number changes from the previous one.
For example, if nums = [1,2,3,4], the answer is 4 because every value is already unique. If nums = [1,1,2], the answer is 2 because the unique values are [1,2]. A larger example like [0,0,1,1,1,2,2,3,3,4] returns 5, because the distinct values are [0,1,2,3,4].
So the task is to compact the sorted array so that each value appears once at the front, then return the count of those unique values.
Example Input & Output
The array already contains unique elements.
The unique elements are [0,1,2,3,4].
The unique elements are [1,2].
Algorithm Flow
Solution Approach
Remove duplicates in-place from a sorted array so each element appears once. Use two pointers: i tracks the last unique position, j scans ahead. When nums[j] differs from nums[i], advance i and copy nums[j] to nums[i]. Return i+1 as the new length.
The sorted order guarantees duplicates are adjacent. The slow pointer i marks the boundary of deduplicated elements.
Time complexity is O(n), space complexity is O(1).
Best Answers
class Solution {
public int remove_duplicates(int[] nums) {
if (nums.length == 0) return 0;
int k = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i-1]) {
nums[k] = nums[i];
k++;
}
}
return k;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
