Junior — Middle
How can you eliminate duplicate elements in a sorted array without resorting to re-sorting?
sobes.tech AI
Answer from AI
If the array is already sorted, then duplicate elements will be adjacent. To remove duplicates without re-sorting, you can iterate through the array once and copy unique elements into a new array or modify the original array in place using two pointers.
Example in Java with in-place modification (for an int array):
public static int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int uniqueIndex = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[uniqueIndex]) {
uniqueIndex++;
nums[uniqueIndex] = nums[i];
}
}
return uniqueIndex + 1; // new length of the array without duplicates
}
In the end, the first uniqueIndex + 1 elements of the array will be unique. This approach works in O(n) time and does not require additional sorting.