Java Program to Find Duplicate Elements in an Array

Introduction

Finding duplicate elements in an array is a common problem in programming, especially in data processing tasks. This guide will show you how to create a Java program that identifies and displays duplicate elements in an array.

Problem Statement

Create a Java program that:

  • Takes an array of integers as input.
  • Finds and displays all duplicate elements in the array.

Example 1:

  • Input: {1, 2, 3, 4, 2, 3, 5}
  • Output: Duplicate elements: 2, 3

Example 2:

  • Input: {5, 5, 6, 7, 8, 8, 9}
  • Output: Duplicate elements: 5, 8

Solution Steps

  1. Initialize the Array: Define an array with a set of integer values.
  2. Use a Nested Loop to Find Duplicates: Compare each element with every other element in the array to find duplicates.
  3. Display the Duplicate Elements: Print the duplicate elements found in the array.

Approach 1: Using Nested Loops

import java.util.Scanner;

/**
 * Java Program to Find Duplicate Elements in an Array using Nested Loops
 * Author: https://www.javaguides.net/
 */
public class DuplicateElementsFinderNestedLoop {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Step 1: Initialize the array
        System.out.print("Enter the number of elements in the array: ");
        int n = scanner.nextInt();
        int[] array = new int[n];

        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < n; i++) {
            array[i] = scanner.nextInt();
        }

        // Step 2: Find and display duplicate elements using nested loops
        System.out.print("Duplicate elements: ");
        boolean hasDuplicates = false;
        for (int i = 0; i < array.length; i++) {
            for (int j = i + 1; j < array.length; j++) {
                if (array[i] == array[j]) {
                    System.out.print(array[i] + " ");
                    hasDuplicates = true;
                    break;
                }
            }
        }
        if (!hasDuplicates) {
            System.out.println("No duplicates found.");
        } else {
            System.out.println();
        }
    }
}

Explanation

  • Input: The program prompts the user to enter the number of elements in the array and the elements themselves.
  • Finding Duplicates: The program uses two nested loops to compare each element with every other element in the array. If a match is found, it is considered a duplicate.
  • Output: The program prints the duplicate elements found in the array. If no duplicates are found, it prints a message indicating this.

Output Example

Enter the number of elements in the array: 7
Enter the elements of the array:
1 2 3 4 2 3 5
Duplicate elements: 2 3

Approach 2: Using a HashSet

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

/**
 * Java Program to Find Duplicate Elements in an Array using HashSet
 * Author: https://www.javaguides.net/
 */
public class DuplicateElementsFinderHashSet {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Step 1: Initialize the array
        System.out.print("Enter the number of elements in the array: ");
        int n = scanner.nextInt();
        int[] array = new int[n];

        System.out.println("Enter the elements of the array:");
        for (int i = 0; i < n; i++) {
            array[i] = scanner.nextInt();
        }

        // Step 2: Find and display duplicate elements using HashSet
        Set<Integer> uniqueElements = new HashSet<>();
        Set<Integer> duplicateElements = new HashSet<>();

        for (int value : array) {
            if (!uniqueElements.add(value)) {
                duplicateElements.add(value);
            }
        }

        // Step 3: Display the duplicate elements
        if (duplicateElements.isEmpty()) {
            System.out.println("No duplicates found.");
        } else {
            System.out.println("Duplicate elements: " + duplicateElements);
        }
    }
}

Explanation

  • Input: The program prompts the user to enter the number of elements in the array and the elements themselves.
  • Finding Duplicates: The program uses a HashSet to track unique elements. As it iterates through the array, any element that is already in the HashSet is considered a duplicate and added to another HashSet called duplicateElements.
  • Output: The program prints the duplicate elements found in the array. If no duplicates are found, it prints a message indicating this.

Output Example

Enter the number of elements in the array: 7
Enter the elements of the array:
5 5 6 7 8 8 9
Duplicate elements: [5, 8]

Conclusion

This Java program provides multiple methods to find duplicate elements in an array, demonstrating different techniques such as nested loops and using a HashSet. Each approach has its own advantages: nested loops are simple to understand but less efficient, while HashSet offers better performance by reducing the number of comparisons. These methods are useful for various data processing tasks in Java where finding duplicates is required.

Comments