I have an unsorted array of integers where the value is ranging from Integer.MIN_VALUE to Integer.MAX_VALUE. There can be multiple duplicates of any integer in the array. I need to return an array with all duplicates removed and also maintain the order of elements.
example:
int[] input = {7,8,7,1,9,0,9,1,2,8}
output should be {7,8,1,9,0,2}
I know this problem can be solved using LinkedHashSet
but I need a solution which doesn't involve significant buffer space.
You can use java 8 Arrays
stream.distinct()
method to get distinct values from array and it will remain the input order onlyOne clever approach is to use a
LinkedHashSet
to represent the input array. ALinkedHashSet
has the properties that it maintains insertion order (linked list behavior), but is also will ignore the same key being inserted again (map behavior). This means that, for example, the value7
will be only be inserted into the list/map once, the first time it occurs. This is the behavior we want.Demo
I tried couple of approaches - using a
Map
and aSet
to arrive at distinct elements. As per the requirement these do not useLinkedHashSet
orLinkedHashMap
. Also, the order is preserved.I used this sample input array in both cases and got the expected output.
INPUT:
int [] arr = new int [] {1, 99, 2, 82, 99, -20, 9, 2, 9, 45, -319, 1};
RESULT:
[1, 99, 2, 82, -20, 9, 45, -319]
The code samples:
Using a Map:
Using a Set:
The Code:
Here is the complete code of my tests I had tried and some results:
Test Results:
The equipment used: Intel CORE i3 processor, Windows 7 64 bit, Java 8
You could use a
HashSet
instead of aLinkedHashSet
, but this still uses a buffer:Just notice that this alters the original array, if you don't want that another call to create a copy would be needed:
int[] copy = Arrays.copyOfRange(arr, 0, arr.length);
Otherwise if you want to do it in place, without any additional buffer, you would have to iterate the array in a nested array via and the complexity would become:
O(n*n)
, which is pretty bad.What about do it straightforwardly like this