Problem: Write a Java program to find and output all duplicates in a given array.

Example:

Input:  [2, 2, 8, 4, 5, 4, 7, 6, 1, 7]
Output: [2, 4, 7]

To get all the duplicates elements in an array, we have to know the count of every element.

For this, we use the HashMap.We store every element and their count pairs in a HashMap and check which of them have count value greater than 1.

Any element having a count value greater than 1 is a potential duplicate.

import java.util.HashMap;
 
class Main {
  public static void main(String[] args) {
    //input array
    int c, array[] = {2, 2, 8, 4, 5, 4, 7, 6, 1, 7};
    
    //declare hashmap
    HashMap<Integer,Integer> count = new HashMap<>();
    
    //loop through the array elements
    for(int i=0; i<array.length; i++){
      //get the frequency of the element
      c = count.getOrDefault(array[i], 0);
      
      //increment the frequency
      count.put(array[i], c+1);
    }
    
    //output all the elements whose frequency(count) is more than 1.
    System.out.print("Duplicates are: ");
    for(Integer num: count.keySet()){
      if(count.get(num)>1)
        System.out.print(num+" ");
    }
    
  }
}

Output:

Duplicates are: 2 4 7

The getOrDefault() method gets the count of an element from the count HashMap.

If the element is new to the HashMap it returns 0.

Using the put() method, we update the old count value of an array element in the HashMap.

Note: We can also use another array to store the count of every array element but it won’t be space-efficient as the size of the array will be fixed and can potentially consume more space than needed.

For example, an array of size 100 having the same element will have a count array of size 100.

Leave a Reply

12 + 3 =