Monday, February 13, 2017

How to find duplicate elements in Array In Java

In this post I am sharing how to detect duplicate values in array using Java Programming. This is one the frequently asked programming interview question in technical interview. I am showing two methods to find duplicate elements in array. Interviewer wants to know your logical thinking how could solve  problems easy way. So, be ready to write programming logic's in efficient and effective manner.

The following are the steps how to detect duplicate values in array:


  • First you need to create and initialize input array
  • Create an empty set and name it as non duplicate set
  • create an empty set and name it as duplicate set
  • Now iterate through each element in the array and check whether non-duplicates contains the element. If it is present add it to the duplicate set
  • If it is not present add it to non duplicate set
  • Finally Print the elements in duplicate set
Method 1:

Now let us see the program to find print duplicate elements in the array

import java.util.HashSet;
import java.util.Set;
class DuplicateElementsArray
{
public static void main(String args[])
{
String duplicate[]=new String[]{"apple","grapes","banana","apple"};
Set nonDuplicatesSet=new HashSet();
Set duplicateSet=new HashSet();
for(String s:duplicate)
{
if(!nonDuplicatesSet.contains(s))
{
nonDuplicatesSet.add(s);
}
else
{
duplicateSet.add(s);
}
}
System.out.println(duplicateSet);
}

Output:


Method 2:


import java.util.HashSet;
import java.util.Set;

class DuplicateValuesInArray
{
public static void main(String args[]){
int[] arr={2,3,4,1,1,5,3};

Set<Integer>set=new HashSet<Integer>();
for(int i=0;i<arr.length;i++)
{
if(set.add(arr[i])==false)
{
System.out.println("Duplicate values:"+arr[i]);
}


Output:

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...