Saturday, April 18, 2020

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/

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...