This is the Java Program to Find Repeated Elements and the Frequency of Repetition.
Given an array of integers, find and print the repeated elements and their frequency of repetition.
Example:
Array: [1,2,3,4,5,5,3]
Output:
Element—–>Frequency
3—–>2
5—–>2
Sort the array, and find the frequency of each repeated element and print it.
Here is the source code of the Java Program to Find Repeated Elements and the Frequency of Repetition. 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 Repeated Elements and the Frequency of Repetition.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class RepeatedElementsFrequency {
// Function to display the repeated elements and their frequencies
static void displayOutput(int[] array){
int i,j,frequency;
for(i=0; i<array.length; i++){
frequency = 1;
for(j=i+1; j<array.length; j++){
if(array[j] == array[i]){
frequency++;
}
else{
break;
}
}
i=j-1;
if(frequency > 1){
System.out.println("The element is " + array[i]
+ " and its frequency is " + frequency);
}
}
}
// 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");
return;
}
}
Arrays.sort(array);
displayOutput(array);
}
}
1. In function displayOutput(), a variable frequency is created.
2. The loop for(i=0; i<array.length; i++) is used to iterate through the array and it initializes frequency to 1 in each iteration.
3. The nested loop for(j=i+1; i<array.length; j++) traverses the remaining part of the array and count the elements frequency.
4. If the frequency is greater than 1, than the element is displayed along with frequency.
Time Complexity: O(n*log(n)) where n is the number of elements in the array.
Case 1 (Simple Test Case): Enter the size of the array 7 Enter array elements 1 2 3 4 5 5 3 The element is 3 and its frequency is 2 The element is 5 and its frequency is 2 Case 2 (Simple Test Case - another example): Enter the size of the array 5 Enter array elements 1 1 1 1 1 The element is 1 and its frequency is 5
Sanfoundry Global Education & Learning Series – Java Programs.
- Apply for Java Internship
- Check Programming Books
- Practice Information Technology MCQs
- Practice BCA MCQs
- Apply for Computer Science Internship