Problem Statement:
Write a Java program to find duplicate elements in an array. For example, duplicate element in {"ONE", "TWO", "THREE", "TWO"} is "TWO".
Program: FindDuplicatesInArray.java
public class FindDuplicatesInArray
{
public static void main(String[] args)
{
String[] Array = {"abc", "def", "mno", "xyz", "pqr", "xyz", "def"};
for (int i = 0; i < Array.length-1; i++)
{
for (int j = i+1; j < Array.length; j++)
{
if( (Array[i].equals(Array[j])) && (i != j) )
{
System.out.println("Duplicate Element : "+Array[j]);
}
}
}
}
}
Output
Duplicate Element : def
Duplicate Element : xyz
Explanation:
In this program, we compare each and every element of an array with other elements. If the program founds any two elements are equal, the program declare them as duplicates. Time Complexity of this program is O(n^2).