This is a coding questions recently asked to one of my reader in a Java Technical interview. Question was to remove duplicates from an integer array without using any collection API classes like Set or LinkedHashSet, which can make this task trivial. In general, if you need to do this for any project work, I suggest better using Set interface, particularly LinkedHashSet, because that also keep the order on which elements are inserted into Set. Only for technical interview perspective, you need to do this using either loops or recursion, depending upon what is your strongest area. In this article, I am sharing a naive solution, which has lots of limitation to be considered as production quality code, It's not the best solution but still a solution. Main problem, while dealing with array is not finding duplicates, it's about removing them. Since array is a static, fixed length data structure, you can not change its length. This means, deleting an element from an array requires creating a new array and copying content into that array. If your input array contains lots of duplicates then this may result in lots of temporary array. It also increase cost of copying contents, which can be very bad. Given this restriction, you need to come out with a strategy to minimize both memory and CPU requirements.
Java Program to remove duplicates from integer array without CollectionIn this program, we have not used any collection class to remove duplicates, earlier, I had shown you a way to remove duplicates from ArrayList, which was using LinkedHashSet. You can still use that solution if interviewer doesn't mention without Collection specifically. All you need to do is to convert your array into ArrayList first then subsequently create a LinkedHashSet from that ArrayList. In this example, we are removing duplicates from array by not copying them into result array, this solution is not actually deleting duplicates instead it replacing it from default value i.e. zero.
That's it about how to remove duplicates from array in Java without using Collection class. As I said before, this solution is not perfect and has some serious limitation, which is an exercise for you to find out. One hint I can give is that, array itself can contain default value as duplicates e.g. 0 for int, even if you use any Magic number e.g. Integer.MAX_VALUE, you can not be certain that they will not be part of input. Regarding removing duplicate permanently from result array, one approach could be to count number of duplicates and then create an array of right size i.e. length - duplicates, and then copying content from intermediate result array to final array, leaving out elements which are marked duplicate.