This is the Java Program to Print Elements Which Occur Odd Number of Times.
Given an array of integers, print all the elements whose frequency are odd.
Example:
Array = [5, 4, 4, 2, 1]
Output: 5 2 1.
Iterate through the array, and for every element, count its frequency in the array using a nested loop, and mark all the occurrences of that element as true in another boolean array, just to avoid repeatedly checking it again. Print the elements if its frequency is odd.
Here is the source code of the Java Program to Print Elements Which Occur Odd Number of Times. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Print Elements Which Occur Odd Number of Times
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class OddFrequencyElements {
// Function to print odd frequency elements
static void printOddFrequencyElements(int[] array){
boolean[] check = new boolean[array.length];
int i,j,count;
for(i=0; i<array.length; i++){
if(!check[i]){
count=1;
for(j=i+1;j<array.length;j++){
if(array[j] == array[i]){
count++;
check[j]=true;
}
}
if(count%2!=0){
System.out.print(array[i] + " ");
}
}
}
}
// Function to read the 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");
return;
}
}
System.out.println("The odd frequency elements are");
printOddFrequencyElements(array);
}
}
1. In function printOddFrequencyElements(), a boolean array check is created to store the status if the array element is already visited or not.
2. The loop for(i=0; i<array.length; i++) iterates through the array.
3. The condition if(!check[i]) checks if the element is already visited.
4. If the element is not visited already, then the count is initialized to 1 and a nested loop for(j=i+1;j<array.length;j++).
5. The elements with odd frequency are printed.
Time Complexity: O(n2) where n is the number of elements in the array.
Case 1 (Simple Test Case): Enter the size of the array 5 Enter array elements 5 4 4 2 1 The odd frequency elements are 5 2 1 Case 2 (Simple Test Case - another example): Enter the size of the array 8 Enter array elements 6 5 5 4 3 2 1 1 The odd frequency elements are 6 4 3 2
Sanfoundry Global Education & Learning Series – Java Programs.
- Practice Programming MCQs
- Apply for Java Internship
- Practice BCA MCQs
- Check Programming Books
- Apply for Computer Science Internship