Duplicate Elements: Find duplicates in an array
This program demonstrates how to find duplicate elements in an array using Java. The algorithm iterates through the array and uses a HashSet
to track seen elements. If an element is found in the HashSet
, it is identified as a duplicate.
Java Program
import java.util.HashSet;
public class DuplicateElements {
/**
* Finds and prints duplicate elements in the given array.
*
* @param array The array to check for duplicates.
*/
public static void findDuplicates(int[] array) {
HashSet<Integer> seen = new HashSet<>();
HashSet<Integer> duplicates = new HashSet<>();
for (int element : array) {
if (!seen.add(element)) {
duplicates.add(element);
}
}
if (duplicates.isEmpty()) {
System.out.println("No duplicates found.");
} else {
System.out.println("Duplicate elements: " + duplicates);
}
}
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6, 7, 2, 3, 8, 9, 10, 10};
findDuplicates(array);
}
}
Explanation
The program includes the following components:
import java.util.HashSet;
: Imports theHashSet
class from the Java Collections Framework.public class DuplicateElements
: Defines the main class.public static void findDuplicates(int[] array)
: Defines a static method that takes an array of integers as input and prints the duplicate elements.HashSet<Integer> seen = new HashSet<>();
: Initializes aHashSet
to keep track of elements that have been encountered in the array.HashSet<Integer> duplicates = new HashSet<>();
: Initializes aHashSet
to store duplicate elements.for (int element : array)
: Iterates through each element in the array.if (!seen.add(element))
: Checks if the element can be added to theseen
set. If it returnsfalse
, it means the element is a duplicate.duplicates.add(element)
: Adds the duplicate element to theduplicates
set.if (duplicates.isEmpty())
: Checks if theduplicates
set is empty and prints an appropriate message.public static void main(String[] args)
: The main method that initializes an array and calls thefindDuplicates
method.
The example array int[] array = {1, 2, 3, 4, 5, 6, 7, 2, 3, 8, 9, 10, 10};
contains the duplicates 2, 3, and 10. When the findDuplicates
method is called, it will print:
No duplicates found. Duplicate elements: [2, 3, 10]
Explanation
- Java Program: The provided Java program utilizes the
HashSet
class to identify duplicate elements in an array. ThefindDuplicates
method iterates through the array, adding each element to aHashSet
calledseen
. If an element cannot be added (because it is already in theseen
set), it is added to aHashSet
calledduplicates
. - Output: The output of the program will list all the duplicate elements found in the array.