0
0
JavaProgramBeginner · 2 min read

Java Program to Find Duplicate Elements in Array

You can find duplicate elements in a Java array by using a HashSet to track seen elements and print those that appear more than once, for example: Set set = new HashSet<>(); for (int num : arr) { if (!set.add(num)) System.out.println(num); }.
📋

Examples

Input[1, 2, 3, 2, 4, 5, 1]
OutputDuplicate elements: 2 1
Input[10, 20, 30, 40]
OutputNo duplicate elements found
Input[]
OutputNo duplicate elements found
🧠

How to Think About It

To find duplicates, you check each element and remember which ones you have seen before. If you see an element again, it means it's a duplicate. Using a set helps because it only keeps unique items, so if adding an element fails, that element is a duplicate.
📐

Algorithm

1
Create an empty set to store unique elements.
2
Create an empty set or list to store duplicates.
3
For each element in the array, try to add it to the unique set.
4
If adding fails (element already in set), add it to duplicates.
5
After checking all elements, print the duplicates or a message if none found.
💻

Code

java
import java.util.HashSet;
import java.util.Set;

public class FindDuplicates {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 2, 4, 5, 1};
        Set<Integer> unique = new HashSet<>();
        Set<Integer> duplicates = new HashSet<>();

        for (int num : arr) {
            if (!unique.add(num)) {
                duplicates.add(num);
            }
        }

        if (duplicates.isEmpty()) {
            System.out.println("No duplicate elements found");
        } else {
            System.out.print("Duplicate elements: ");
            for (int dup : duplicates) {
                System.out.print(dup + " ");
            }
            System.out.println();
        }
    }
}
Output
Duplicate elements: 1 2
🔍

Dry Run

Let's trace the array [1, 2, 3, 2, 4, 5, 1] through the code to find duplicates.

1

Start with empty sets

unique = {}, duplicates = {}

2

Process element 1

unique.add(1) succeeds, unique = {1}, duplicates = {}

3

Process element 2

unique.add(2) succeeds, unique = {1, 2}, duplicates = {}

4

Process element 3

unique.add(3) succeeds, unique = {1, 2, 3}, duplicates = {}

5

Process element 2 again

unique.add(2) fails, duplicates.add(2), duplicates = {2}

6

Process element 4

unique.add(4) succeeds, unique = {1, 2, 3, 4}, duplicates = {2}

7

Process element 5

unique.add(5) succeeds, unique = {1, 2, 3, 4, 5}, duplicates = {2}

8

Process element 1 again

unique.add(1) fails, duplicates.add(1), duplicates = {1, 2}

ElementUnique SetDuplicates Set
1{1}{}
2{1, 2}{}
3{1, 2, 3}{}
2{1, 2, 3}{2}
4{1, 2, 3, 4}{2}
5{1, 2, 3, 4, 5}{2}
1{1, 2, 3, 4, 5}{1, 2}
💡

Why This Works

Step 1: Use a set to track unique elements

A HashSet stores only unique values, so adding a new element returns true if it was not present before.

Step 2: Detect duplicates by failed add

If adding an element to the set returns false, it means the element is already there, so it is a duplicate.

Step 3: Store duplicates separately

We keep duplicates in another set to avoid printing the same duplicate multiple times.

Step 4: Print results

If duplicates set is empty, print no duplicates found; otherwise, print all duplicates.

🔄

Alternative Approaches

Using nested loops
java
public class FindDuplicatesNested {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 2, 4, 5, 1};
        boolean foundDuplicate = false;
        System.out.print("Duplicate elements: ");
        for (int i = 0; i < arr.length; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] == arr[j]) {
                    System.out.print(arr[i] + " ");
                    foundDuplicate = true;
                    break;
                }
            }
        }
        if (!foundDuplicate) {
            System.out.println("No duplicate elements found");
        }
    }
}
Simple but inefficient for large arrays because it checks every pair.
Using sorting
java
import java.util.Arrays;

public class FindDuplicatesSorted {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 2, 4, 5, 1};
        Arrays.sort(arr);
        boolean foundDuplicate = false;
        System.out.print("Duplicate elements: ");
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] == arr[i - 1]) {
                System.out.print(arr[i] + " ");
                foundDuplicate = true;
            }
        }
        if (!foundDuplicate) {
            System.out.println("No duplicate elements found");
        }
    }
}
Faster than nested loops but modifies the original array.

Complexity: O(n) time, O(n) space

Time Complexity

The program loops through the array once, and each set operation is O(1) on average, so total time is O(n).

Space Complexity

Extra space is used for the sets to store unique and duplicate elements, which can be up to O(n) in the worst case.

Which Approach is Fastest?

Using a HashSet is fastest for large arrays compared to nested loops (O(n^2)) or sorting (O(n log n)).

ApproachTimeSpaceBest For
HashSetO(n)O(n)Large arrays, fast lookup
Nested loopsO(n^2)O(1)Very small arrays or no extra space
SortingO(n log n)O(1) or O(n)When modifying array is allowed
💡
Use a HashSet to track seen elements for an efficient duplicate check.
⚠️
Forgetting to handle the case when no duplicates are found and printing nothing.