Java Program to find duplicate elements in an Array

By | December 7, 2018

In this post of Java Program to find duplicate elements in an Array. we will see couple of approaches/methods to find duplicate elements in the given array.

If you want to find duplicate elements in an array, then you have to loop through an array taking one element at a time and then to compare it with all other elements of the array to find duplicates. Although this solution works well, but the problem here is that you are looping, although the array is making the time complexity of this solution O(n2). Because of the double iteration program will be slow.

To minimize the execution time We can  use a data structure like HashSet which will reduce the time complexity to O(n).

You may also like –

How to convert number to words in java
How to swap two numbers with or without temporary variable in java
How to reverse a number in Java
How to check Armstrong number java program
Java program to find factorial of a number

As we know that Set doesn’t allow duplicate elements if we try to do that will return false. So we can have a logic where  iterate an array and try to add element to the HashSet, if adding an element to the HashSet returns false that means a duplicate element is present in that array. As I said above since array is iterated only once so time complexity would be  O(N) here but as a new data structure is created, apart from array we are also creating a Set, so space complexity increases here, extra space used is O(N).

Let’s have a Java program to find duplicate elements in an array using both of the approaches discussed above.

Looping through Array and comparing elements

In this example We have an outer loop that iterates the array one element at a time and another loop that starts from the next element and iterates through all the elements of the array and compares.

Using java.util.HashSet to find duplicate elements in an array

In this example to find duplicate elements in an array in We iterated  the array  and elements of the array are added to the Set.

Here We need to  understand on thing – If set already contains the element, calling to add method of the Set leaves the set unchanged and returns false. 
So, whenever false is returned that means a duplicate element is present in the array.

That’s all about this topic Java Program to find duplicate elements in an Array. If you have any doubts or any suggestions to make please drop a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *