How to find Duplicate Element in an Array of Integers?Java Programming Language

Search Results

Featured snippet from the web

Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.
Example 1:
 int a[]={2,6 ,7,2,8,6};

Here 2 and 6 are the duplicate elements.

Example 2:
int a[]={5,3,6,2,6,9,5}

Here 6 and 5 are the duplicate elements.

Source Code:

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

//Brute force approach

public class DuplicateInArray {

    public static void Duplicate(int a[]){
        
        for(int i=0;i<a.length-1;i++){
            
            for(int j=i+1;j<a.length;j++){
                
                if(a[i]==a[j]){
                    //if above condition is true then element is duplicate and then we print it
                    System.out.println(a[j]);
                }
                
            }
        }
    }
    
    //Using hashset
    
    public static void Duplicate1(int a[]){
        
        HashSet<Integer> hs=new HashSet<>();
        
        for(int no:a){
            boolean b=hs.add(no);
            
            if(b==false){
                System.out.println(no);
            }
            
        }
    }
    
    //using Hashmap-Efficient solution
    
    public static void Duplicate2(int a[]){
        
        HashMap<Integer,Integer> map=new HashMap<>();
        
        for(int no:a){
            
            Integer count=map.get(no); 
            if(count==null){
                map.put(no,1);
                
            }
            else{
                count=count+1;
                map.put(no,count);
            }
        }
        
        Set<Map.Entry<Integer,Integer>>es=map.entrySet();//converting map to set usign entrySet
        
        for(Map.Entry<Integer,Integer> me:es){
        
            if(me.getValue()>1){
                System.out.println(me.getKey());
            }
    }
    }
    
   
   
    public static void main(String[] args) {
        
        int a[]={2,6,4,2,8,6,9,8};
        
        System.out.println("Duplicate elements are");
        
        
        Duplicate(a);
         System.out.println("Duplicate elements are");
        Duplicate1(a);
        
         System.out.println("Duplicate elements are");
        Duplicate2(a);
    }
    
}

Hence these are the different approaches to solve problem of duplicate elements in an array of integers.

Comments