Java puzzle – Find all the duplicate elements

Puzzle: Given an input array of n positive integers where the integers are in random order. Each number in that array can occur many times. You need to find all the distinct elements and put all those elements in an array i.e. output1. If no number is duplicated in input, then output should be {-1}.

Input Specifications: input: number of elements in input2 (n) input 2: an array of n positive integers

Output Specifications: output: an array of distinct elements which are duplicate in input2

Example 1: input : 6 input2 : {4,4,7,8,8,9} output : {4,8} 
Example 2: input : {2,3,6,8,90,58,58,60} output : {58} 
Example 3: input : {3,6,5,7,8,19,32} output : {-1}

Solution

import java.util.HashSet;
import java.util.Set;
 
public class DuplicatesInArray
{
    public static void main(String[] args)
    {
        Integer[] array = {1,2,3,4,5,6,7,8};  //input 1
        int size = array.length;              //input 2
         
        Set<Integer> set = new HashSet<Integer>();
        Set<Integer> duplicates = new HashSet<Integer>();
          
        for(int i = 0; i < size ; i++)
        {
            if(set.add(array[i]) == false)
            {
                duplicates.add(array[i]);
            }
        }
         
        if(duplicates.size() == 0)
        {
            duplicates.add(-1);
        }
         
        System.out.println(duplicates);
    }
}

The above program will find all duplicate elements from the array and put them into a separate set. You can find more discussion on this logic here: //howtodoinjava.com/java/interviews-questions/find-duplicate-elements-in-an-array/

Happy Learning !!

Leave a Reply

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial