Thursday 15 June 2023

How to find the duplicate elements in java array ?

To find duplicate elements in an array in Java, you can use various approaches. Here are a few commonly used methods:

  1. Using Brute Force: You can use a nested loop to compare each element of the array with all other elements and check for duplicates. If a duplicate is found, you can store or print the element.

    java
    int[] array = {1, 2, 3, 4, 2, 5, 1}; for (int i = 0; i < array.length - 1; i++) { for (int j = i + 1; j < array.length; j++) { if (array[i] == array[j]) { System.out.println("Duplicate element: " + array[i]); } } }
  2. Using HashSet: You can utilize a HashSet to keep track of unique elements encountered in the array. When adding elements to the HashSet, if an element is already present, it indicates a duplicate.

    java
    int[] array = {1, 2, 3, 4, 2, 5, 1}; Set<Integer> uniqueElements = new HashSet<>(); Set<Integer> duplicateElements = new HashSet<>(); for (int num : array) { if (!uniqueElements.add(num)) { duplicateElements.add(num); } } System.out.println("Duplicate elements: " + duplicateElements);
  3. Using HashMap: You can utilize a HashMap to store the frequency of each element in the array. If the frequency exceeds 1, it indicates a duplicate element.

    java
    int[] array = {1, 2, 3, 4, 2, 5, 1}; Map<Integer, Integer> elementFrequency = new HashMap<>(); for (int num : array) { elementFrequency.put(num, elementFrequency.getOrDefault(num, 0) + 1); } for (Map.Entry<Integer, Integer> entry : elementFrequency.entrySet()) { if (entry.getValue() > 1) { System.out.println("Duplicate element: " + entry.getKey()); } }

These are a few approaches to find duplicate elements in an array in Java. Choose the one that suits your requirements and the size of the array. 

No comments:

Post a Comment