Find Duplicate Elements in an Array – Java Program

Write a java program to find duplicate elements in an array. Given an array of integers, We have to write a code to find all duplicate elements in an array.

For example :

Input : arr = { 2, 5, 3, 1, 8, 7, 5, 3, 2 }

Output: {5, 3, 2}

In this tutorial, I am going to explain three approaches to find duplicate elements in an array. This question is also very important for technical interviews.

Find Duplicate Elements in an Array - Java Program

Find Duplicate Elements in an Array – Java Program

How to Find Duplicate Elements in an Array

METHOD 1 – Using brute force approach

This is the most basic and easiest approach to find and print duplicate elements of an array. In this approach, we use two for loops (inner and outer loops) to compare an element with each element of an array.

The time complexity of this approach is O(n2).

This approach is not suitable for large data sets.

Find Duplicate Elements in an Array using HashMap

This approach is much better than the brute force approach.

Java program to find first non-repeated character in a string

In this approach, we traverse an array and create a map of array element and it’s count. Then, Traverse a map to check all the keys whose value is greater than 1. Those keys whose value is greater than 1 are duplicate elements in an array.

The Time complexity of this approach is O(n).

Find Duplicate Elements in an Array using Set

The set data structure doesn’t allow duplicates. In java, we take the advantage of  set to identify duplicate elements of an array.

Traverse an array and insert an element into Set using the add() method. If the add() method returns false, it means that element is already present in set.

The time complexity of this approach is O(n).

In these video tutorials, I have explained how we can find all duplicates in an array.

Conclusion

I have explained three methods to solve this problem. If you know some other approach to solve this problem, then you can let us know through your comments.

Tagged , , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.