Remove duplicates in ordered array Java
Heres how to remove duplicates from an ordered primitive int array on Java.
You can find the complete code for this here: remove_dupes.jsh.
Consider the following problem, you have to remove the duplicates from an ordered integer array
Since you cant actually change the length of a primitive array in java without declaring a new one, you will return the new length the array would have without the duplicates.
In order to solve this in O(n) time and O(1) space we are going to use a
two pointer technique.
We will have
j that will increase by one in every iteration and
i which will increase only if its different from the value which j points to, ignoring every duplicate found.
This doesn’t account for a null, or less than a lenght 2 array (in which case we could start j at 0).
The pre-increment could be less readable but just remember that
++variable means we are increasing first and then using the variable.
Download the complete code from this post here: remove_dupes.jsh.