Problem: Remove Duplicates from Sorted Array
Let’s focus on the problem of removing duplicates from a sorted array.
Let’s clarify the requirement: in-place means we cannot use another array to store the unique elements; we must modify the input array nums directly.
The convention for this problem is to keep the unique elements in the first part of the array and return the count of unique elements. The rest of the array can be left with any values, because they will be ignored. This is a common convention for in-place array problems, because in some languages you cannot change the length of an array.
So you can consider the function signature to be:
public static int removeDuplicates(int[] nums) {
// Your implementation goes here
}
Here are some examples to better understand the problem:
Example 1:
Suppose the input is nums = [1,1,2]. The unique values are 1 and 2, so k = 2. You must leave nums[0] holding 1 and nums[1] holding 2, and then return 2. Only the first k slots are checked, so nums[2] can hold anything. We write that as [1,2,_], where _ stands for a value that will be ignored.
That means there is more than one correct final array here. You could swap the second 1 with the 2 and end up with [1,2,1]. You could copy the 2 over the second 1 and end up with [1,2,2].
Example 2:
If the input is nums = [0,0,1,1,1,2,2,3,3,4], the unique values are 0,1,2,3,4, so k = 5. You should leave the array as [0,1,2,3,4,_,_,_,_,_] and return 5.
I recommend trying to solve this problem without worrying about how efficient your solution is at first. Just focus on correctness and respect the in-place requirement. That is what I will do next. After that, I will show you a faster solution.