This is the Java Program to Find the Elements that do Not have Duplicates.
Given an array, print all the elements whose frequency is one, that is they do not have duplicates.
Example:
Array = [-1, -2, 3, 3, -2]
Output = -1
Traverse through the array and find the frequency of each element, if the frequency is one, then print the element.
Here is the source code of the Java Program to Find the Elements that do Not have Duplicates. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Find the Elements that do Not have Duplicates
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class NoDuplicates {
// Function to print elements with no duplicates
static void printElementsWithNoDuplicates(int[] array){
int i,j;
int count;
int x = 0;
boolean[] flag = new boolean[array.length];
for(i=0; i<array.length; i++){
if(!flag[i]){
count = 1;
for(j=i+1; j<array.length;j++){
if(array[j] == array[i])
{
count++;
flag[j] = true;
}
}
if(count == 1){
System.out.println(array[i]);
x++;
}
}
}
if(x==0){
System.out.println("All elements are repeated");
}
}
// Function to read input
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int size;
System.out.println("Enter the size of the array");
try {
size = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("Invalid Input");
return;
}
int[] array = new int[size];
System.out.println("Enter array elements");
int i;
for (i = 0; i < array.length; i++) {
try {
array[i] = Integer.parseInt(br.readLine());
} catch (Exception e) {
System.out.println("An error Occurred");
}
}
System.out.println("The elements are ");
printElementsWithNoDuplicates(array);
}
}
1. In function printElementsWithNoDuplicates(), an array of boolean is created to keep track of the elements which are visited.
2. The loop for(i=0; i<array.length; i++) is used to iterate through the array.
3. The condition if(!flag[i]) is used to check whether the element is not visited already.
4. If true, then the nested loop for(j=i+1; j<array.length;j++) is used to find the frequency of the element.
5. If the frequency is 1, then the element is printed.
6. If every element has a duplicate, then a suitable message is displayed.
Time Complexity: O(n2) where n is the number of elements in the array.
Case 1 (Simple Test Case - some elements are unique): Enter the size of the array 6 Enter array elements 1 2 3 4 5 5 The elements are 1 2 3 4 Case 2 (Simple Test Case - all elements have a duplicate): Enter the size of the array 6 Enter array elements 1 2 3 3 2 1 The elements are All elements are repeated
Sanfoundry Global Education & Learning Series – Java Programs.
- Check Programming Books
- Check Java Books
- Apply for Java Internship
- Practice Information Technology MCQs
- Practice BCA MCQs