I am working on this famous interview question on removing duplicate elements in array
without using auxillary storage
and preserving the order;
I have read a bunch of posts; Algorithm: efficient way to remove duplicate integers from an array, Removing Duplicates from an Array using C.
They are either implemented in C
(without explanation) or the Java Code
provided just fails when there is consecutive duplicates such as [1,1,1,3,3]
.
I am not quite confident with using C
, my background is Java
. So I implemented the code myself;
it follows like this:
- use two loops, the outer-loop traverses the array and inner loop checks for duplicates and if present replace it with null.
- Then I go over the duplicate-replaced-null array and remove null elements and replacing it with the next non-null element.
The total run-time I see now is
O(n^2)+O(n) ~ O(n^2)
. Reading the above posts, I understood this is the best we can do, if no sorting and auxiliary storage is allowed. My code is here: I am looking for ways to optimize any further (if there is a possibility) or abetter/simplisitc logic
;public class RemoveDup { public static void main (String[] args){ Integer[] arr2={3,45,1,2,3,3,3,3,2,1,45,2,10}; Integer[] res= removeDup(arr2); System.out.println(Arrays.toString(res)); } private static Integer[] removeDup(Integer[] data) { int size = data.length; int count = 1; for (int i = 0; i < size; i++) { Integer temp = data[i]; for (int j = i + 1; j < size && temp != null; j++) { if (data[j] == temp) { data[j] = null; } } } for (int i = 1; i < size; i++) { Integer current = data[i]; if (data[i] != null) { data[count++] = current; } } return Arrays.copyOf(data, count); }
}
EDIT 1; Reformatted code from @keshlam throws ArrayIndexOutofBound Exception:
private static int removeDupes(int[] array) {
System.out.println("method called");
if(array.length < 2)
return array.length;
int outsize=1; // first is always kept
for (int consider = 1; consider < array.length; ++consider) {
for(int compare=0;compare<outsize;++compare) {
if(array[consider]!=array[compare])
array[outsize++]=array[consider]; // already present; advance to next compare
else break;
// if we get here, we know it's new so append it to output
//array[outsize++]=array[consider]; // could test first, not worth it.
}
}
System.out.println(Arrays.toString(array));
// length is last written position plus 1
return outsize;
}