This post will discuss how to check for duplicates in an array in Java.

1. Naive Solution

A naive solution is to check if every array element is repeated or not using nested for-loops. The time complexity of this solution would be O(n2).

Download  Run Code

2. Using HashSet

We can perform better by using Hashing. The idea is to traverse the given array and insert each encountered element into a HashSet. Now, if the encountered element was already present in the set, it is a duplicate. The time complexity of this solution is O(n) but auxiliary space used is O(n).

Download  Run Code

We know that HashSet doesn’t allow duplicate values in it. We can make use of this property to check for duplicates in an array. The idea is to insert all array elements into a HashSet. Now the array contains a duplicate if the array’s length is not equal to the set’s size.

Download  Run Code

3. Using Sorting

The idea is to sort the array in natural or reverse order. Now we traverse the array and compare adjacent elements. If any adjacent element is found to be the same, we can say that the array contains a duplicate. The time complexity of this solution is O(n.log(n)).

Download  Run Code

4. Using Java 8

In Java 8, we can make use of streams to count distinct elements present in the array. If the distinct count is not the same as the array’s length, the array contains a duplicate.

Download  Run Code

That’s all about checking for duplicates in an array in Java.