Duplicate element in Array

Very often question may be asked in education or in any interview is to find the duplicate element in array. Here is an example to find it using java. I have describe it by two ways there can be lots of ways but this two methods I have found usable.

public class DuplicateInArray{
public static void main(String[] args){
String[] arr1 = {"Test","Hi", "Test","Hello","test","Hi"};

// Using Brute force method
System.out.println("Using Brute force method\n============================");
for(int i=0; i < arr1.length-1; i++){
for(int j=i+1; j < arr1.length; j++){
if( (arr1[i].equals(arr1[j])) && (i != j) ){
System.out.println(arr1[i] + " : " + arr1[j]);
}
}
}

//Using Hash set method
System.out.println("\nUsing Hash set method\n============================");
java.util.HashSet<String> set = new java.util.HashSet<String>();
for(String element : arr1){
if(!(set.add(element))){
System.out.println(element);
}
}

System.out.println(set);
}
}

Write the above program and save it as DuplicateInArray.java and compile it as javac DuplicateInArray.java and execute it as java DuplicateInArray.

No comments:

Post a Comment