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 !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

2 thoughts on “Java puzzle – Find all the duplicate elements”

  1. List input = Arrays.asList(1, 2, 5, 2, 5, 5, 1, 6, 9);
    
    Map frequencies = input.stream()
         .collect(Collectors.groupingBy(n -&gt; n, Collectors.counting()));
    
    frequencies.entrySet().stream()
        .filter(entry -&gt; entry.getValue() &gt; 1)
        .forEach(System.out::println);
    Reply
  2. A better approach with stream will be

            Set<Integer> uniques = new HashSet<>();
            Set<Integer> collect = duplicates.stream()
                    .filter(integer -> !uniques.add(integer))
                    .collect(Collectors.toSet());
    

    or

            Set<Integer> collect  = duplicates.stream()
                    .filter(integer -> Collections.frequency(duplicates, integer) > 1)
                    .collect(Collectors.toSet());
    
    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.