Java program to find the frequency of elements in an array
Frequency of Element in Java
Here, on this page, we will discuss the program to find the frequency of elements in Java programming language. We are given an array and need to print the frequency of each given element.
Java program to find the frequency of each element in the array
Methods Discussed are :
Objective: Java Program to find the Frequency of each element in the Array.
- Method 1 : Using Naive Approach with extra space.
- Method 2 : Naive way without extra space.
- Method 3 : Using Sorting
- Method 4 : Using hash Map
Let’s discuss each method one by one,
Method 1 :
In this method we will count the frequency of each elements using two for loops.
- To check the status of visited elements create a array of size n.
- Run a loop from index 0 to n and check if (visited[i]==1) then skip that element.
- Otherwise create a variable count = 1 to keep the count of frequency.
- Run a loop from index i+1 to n
- Check if(arr[i]==arr[j]), then increment the count by 1 and set visited[j]=1.
- After complete iteration of for loop print element along with value of count.
Time and Space Complexity :
- Time Complexity : O(n2)
- Space Complexity : O(n)
Method 1: Code in Java
import java.util.Arrays; class Main { public static void countFreq(int arr[], int n) { boolean visited[] = new boolean[n]; Arrays.fill(visited, false); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { // Skip this element if already processed if (visited[i] == true) continue; // Count frequency int count = 1; for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true; count++; } } System.out.println(arr[i] + " occurs " + count +" times "); } } // Driver code public static void main(String []args) { int arr[] = new int[]{10, 30, 10, 20, 10, 20, 30, 10}; int n = arr.length; countFreq(arr, n); } }
Output
10 occurs 4 times
30 occurs 2 times
20 occurs 2 times
Method 2 :
In this method we will use the naive way to find the frequency of elements in the given integer array without using any extra space.
Method 2 : Code in Java
// Time Complexity : O(n^2) // Aux Space Complexity : O(1) import java.lang.*; class Main { public static void main (String[] args) { int[] arr = {5, 8, 5, 7, 8, 10}; int size = arr.length; countFrequency(arr, size); } static void countFrequency(int[] array, int size) { for (int i = 0; i < size; i++){ int flag = 0; int count = 0; for (int j = i+1; j < size; j++){ if (array[i] == array[j]){ flag = 1; break; } } // The continue keyword is used to end the current iteration // in a for loop (or a while loop), and continues to the next iteration if (flag == 1) continue; for (int j = 0;j<=i;j++){ if (array[i] == array[j]) count++; } System.out.println(array[i]+": "+count); } } }
Output
5 : 2
7 : 1
8 : 2
10 : 1
Method 3 :
In this method we will sort the array then, count the frequency of the elements.
Time and Space Complexity :
- Time Complexity : O(nlogn)
- Space Complexity : O(1)
Method 3 : Code in Java
import java.lang.*; import java.util.Arrays; class Main { public static void main (String[] args) { int[] arr = {5, 8, 5, 7, 8, 10}; int size = arr.length; countFrequency(arr, size); } static void countFrequency(int[] arr, int n) { Arrays.sort(arr); // Traverse the sorted array for (int i = 0; i < n; i++) { int count = 1; // Move the index ahead whenever // you encounter duplicates while (i < n - 1 && arr[i] == arr[i + 1]) { i++; count++; } System.out.println(arr[i] + ": " + count); count++; } } }
Output
5 : 2
7 : 1
8 : 2
10 : 1
Method 4 :
In this method we will count use hash-map to count the frequency of each elements.
- Declare a hash map.
- Start iterating over the entire array
- If element is present in map, then increase the value of frequency by 1.
- Otherwise, insert that element in map.
- After complete iteration over array, start traversing map and print the key-value pair.
Time and Space Complexity :
- Time Complexity : O(n)
- Space Complexity : O(n)
Method 4 : Code in Java
import java.util.*; import java.util.Arrays; class Main { static void countFreq(int arr[], int n) { Map<Integer, Integer> mp = new HashMap<>(); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { if (mp.containsKey(arr[i])) { mp.put(arr[i], mp.get(arr[i]) + 1); } else { mp.put(arr[i], 1); } } // Traverse through map and print frequencies for (Map.Entry<Integer, Integer> entry : mp.entrySet()) { System.out.println(entry.getKey() + " occurs " + entry.getValue()+" times "); } } // Driver code public static void main(String []args) { int arr[] = new int[]{10, 30, 10, 20, 10, 20, 30, 10}; int n = arr.length; countFreq(arr, n); } }
Output
20 occurs 2 times
10 occurs 4 times
30 occurs 2 times
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
mportant Codes related to Arrays
- Find Smallest Element in an Array : C | C++ | Java | Python
- Find Second Smallest Element in an Array : C | C++ | Java | Python
- Find Largest element in an array : C | C++ | Java | Python
- Find the Smallest and largest element in an array : C | C++ | Java | Python
- Calculate the sum of elements in an array : C | C++ | Java | Python
- Reverse an Array : C | C++ | Java | Python
- Sort first half in ascending order and second half in descending : C | C++ | Java | Python
- Sort the elements of an array : C | C++ | Java | Python
- Finding the frequency of elements in an array : C | C++ | Java | Python
- Sorting elements of an array by frequency : C | C++ | Java | Python
- Finding the Longest Palindrome in an Array : C | C++ | Java| Python
- Counting Distinct Elements in an Array : C | C++ | Java| Python
- Finding Repeating elements in an Array : C | C++ | Java | Python
- Finding Non Repeating elements in an Array : C | C++ | Java | Python
- Removing Duplicate elements from an array : C | C++ | Java | Python
- Finding Minimum scalar product of two vectors : C | C++ | Java | Python
- Finding Maximum scalar product of two vectors in an array : C | C++ | Java | Python
- Counting the number of even and odd elements in an array : C | C++ | Java | Python
- Find all Symmetric pairs in an array : C | C++ | Java | Python
- Find maximum product sub-array in a given array : C | C++ | Java | Python
- Finding Arrays are disjoint or not : C | C++ | Java | Python
- Determine Array is a subset of another array or not : C | C++ | Java | Python
- Determine can all numbers of an array be made equal : C | C++ | Java | Python
- Finding Minimum sum of absolute difference of given array : C | C++ | Java | Python
- Sort an array according to the order defined by another array : C | C++ | Java | Python
- Replace each element of the array by its rank in the array : C | C++ | Java | Python
- Finding equilibrium index of an array : C | C++ | Java| Python
- Rotation of elements of array- left and right : C | C++ | Java| Python
- Block swap algorithm for array rotation : C | C++ | Java| Python
- Juggling algorithm for array rotation : C | C++ | Java | Python
- Finding Circular rotation of an array by K positions : C | C++ | Java | Python
- Balanced Parenthesis Problem : C | C++ | Java | Python
Login/Signup to comment
int[]a={2,3, 4, 1,2,3,4, 5, 6,4};
Mapmap=new HashMap();
for(int i=0;i<a.length;i++){
if(!map.containsKey(a[i])){
map.put(a[i],1);
}else{
map.put(a[i],map.getOrDefault(a[i],0)+1);
}
}
for(Map.Entrye:map.entrySet()){
System.out.println(“[“+e.getKey()+” count = “+e.getValue()+”] “);
}
package arrays;
import java.util.Scanner;
public class PrepInsta
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int[] arr = new int[100];
int[] freq = new int[100];
int size, k, j, count;
// Input size of array
System.out.print( “Enter size of array: “);
size = sc.nextInt();
/* Input elements in array */
System.out.print( “Enter elements in array:”);
for(k=0; k<size; k++)
{
arr[k] = sc.nextInt();
// Initially initialize frequencies to -1
freq[k] = -1;
}
for(k=0; k<size; k++)
{
count = 1;
for(j=k+1; j<size; j++)
{
// If duplicate element is found
if(arr[k]==arr[j])
{
count++;
// Make sure not to count frequency of same element again
freq[j] = 0;
}
}
// If frequency of current element is not counted
if(freq[k] != 0)
{
freq[k] = count;
}
}
// Print frequency of each element
System.out.println( "Frequency of all elements of array");
for(k=0; k<size; k++)
{
if(freq[k] != 0)
{
System.out.println(arr[k] + "occurs" + freq[k] + " times" + "");
}
}
}
}
//fixed code ————————–
public class PrepInsta
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int[] arr = new int[100];
int[] freq = new int[100];
int size, k, j, count;
// Input size of array
System.out.print( “Enter size of array: “);
size = sc.nextInt();
/* Input elements in array */
System.out.print( “Enter elements in array:”);
for(k=0; k<size; k++)
{
arr[k] = sc.nextInt();
// Initially initialize frequencies to -1
freq[k] = -1;
}
for(k=0; k<size; k++)
{
count = 1;
for(j=k+1; j<size; j++)
{
// If duplicate element is found
if(arr[k]==arr[j])
{
count++;
// Make sure not to count frequency of same element again
freq[j] = 0;
}
}
// If frequency of current element is not counted
if(freq[k] != 0)
{
freq[k] = count;
}
}
// Print frequency of each element
System.out.println( "Frequency of all elements of array");
for(k=0; k<size; k++)
{
if(freq[k] != 0)
{
System.out.println(arr[k] + "occurs" + freq[k] + " times" + "");
}
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[]= {1,2,3,5,2,7,3,5};
int n=a.length;
//create a frequency array to count the elements
int freq[]=new int[n];
for(int i=0;i<n;i++) {
int index= a[i];
freq[index]=freq[index]+1;
}
for(int i=0;i<n;i++) {
if(freq[i]!=0) {
System.out.println(i +"comes :" +freq[i]+ "times");
}
}
}
#include
using namespace std;
int main()
{
int size;
cin>>size;
int arr[size];
int freq[size];
for(int i=0; i>arr[i];
freq[i] = -1;
}
int count = 1;
for(int i=0; i<size-1; i++)
{
count = 1;
for(int j=i+1; j<size; j++)
{
if(arr[i]==arr[j])
{
count++;
freq[j] = 0;
}
}
if(freq[i] !=0)
{
freq[i] = count;
}
}
for(int k=0; k<size; k++)
{
if(freq[k] !=0)
{
cout<<arr[k]<<" : "<<freq[k]<<endl;
}
}
return 0;
}
#include //line1
map mp;//line 4
#include
using namespace std;
int main() {
// your code goes here
map mp;
int n;
cin>>n;
int a[n];
for(int i=0;i>a[i];
}
for(int i=0;i<n;i++)
{
mp[a[i]]++;
}
for(auto it=mp.begin();it!=mp.end();it++)
{
cout<first<<" is occure "<second<<"times"<<endl;
}
return 0;
}
//in JS:
const findFreqs = (str = "") => {
if (str.length === 0) {
return "";
}
let arr = str.split('')
let hs = {};
let l = arr.length;
for (let i = 0; i = 0 || hs[arr[i]] <= 0) {
hs[arr[i]] = hs[arr[i]] + 1;
} else {
hs[arr[i]] = 1;
}
}
let result = '';
for (const e of Object.entries(hs)) {
const [key, value] = e;
const s = `${key}${value} `;
result = result + s;
}
result = result.trim();
return result;
}
#include
#include
using namespace std;
int main(){
int N,countr,j=0,arr[200],visited[200];
cin>>N;
for(int i=0;i>arr[i];
}
for(int i=0;i<N;i++){
if(i==0){
countr=count(arr,arr+N,arr[0]);
visited[j]=arr[0];
cout<<arr[i]<<" "<<countr<<endl;
j++;
}
else if(binary_search(visited,visited+j,arr[i])==false){
countr=count(arr,arr+N,arr[i]);
visited[j]=arr[i];
cout<<arr[i]<<" "<<countr<<endl;
j++;
}
}
}
where can I find this code in c?
Hey Kandukuri, we don’t have this code in C, we’ll work on it asap, it’ll be really helpful if you can provide us with the code, and we’ll post your code on our page
//This code works in C
#include
int main()
{
int n,i;
scanf(“%d”,&n);
int a[n],c[100]={0};
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
c[a[i]]++;
}
for(i=0;i<n;i++)
{
if(c[i]!=0)
{
printf("%d\n",c[i]);
}
}
return 0;
}
//IN C
#include
int main()
{
int n,i;
scanf(“%d”,&n);
int a[n],c[100]={0};
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
c[a[i]]++;
}
for(i=0;i<100;i++)
{
if(c[i]!=0)
{
printf("%d occurs %d times\n",i,c[i]);
}
}
return 0;
}
Your website is very slow
yeah we are working on that
There are some errors in the code
Hey Rajpriya, can you tell us what errors have you found.
# correct program after compile and run.
import java.util.*;
public class Arrayopertion {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println(“Enter no of elements :”);
int n=sc.nextInt();
int a[]=new int[n];
int freq[]=new int[n];
System.out.println(“Enter array elements: “);
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
freq[i]=-1;
}
for(int i=0;i<n;i++)
{
int count=1;
for(int j=i+1;j<n;j++)
{
if(a[i]==a[j])
{
count++;
freq[j]=0;
}
}
if(freq[i]!=0)
{
freq[i]=count;
}
}
System.out.println("Frequency of a number in array: ");
for(int i=0;i<n;i++)
{
if(freq[i]!=0)
{
System.out.println(a[i]+" occurs "+freq[i]+" times in array");
}
}
}
}
public class Main
{
public static void main(String[] args)
{
int [] arr = new int [] {1, 2, 8, 3, 2, 2, 2, 5, 1, 5, 7, 3, 5, 9, 8};
int [] fr = new int [arr.length];
int visited = -1;
for(int i = 0; i < arr.length; i++)
{
int count = 1;
for(int j = i+1; j < arr.length; j++)
{
if(arr[i] == arr[j])
{
count++;
fr[j] = visited;
}
}
if(fr[i] != visited)
fr[i] = count;
}
System.out.println("—————————————");
System.out.println(" Element | Frequency");
System.out.println("—————————————");
for(int i = 0; i < fr.length; i++){
if(fr[i] != visited)
System.out.println(" " + arr[i] + " | " + fr[i]);
}
System.out.println("—————————————-");
}
}
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int[] arr = new int[100];
int[] freq = new int[100];
int size, i, j, count;
// Input size of array
System.out.print( “Enter size of array: “);
size = sc.nextInt();
/* Input elements in array */
System.out.print( “Enter elements in array:”);
for(i=0; i<size; i++)
{
arr[i] = sc.nextInt();
// Initially initialize frequencies to -1
freq[i] = -1;
}
for(i=0; i<size; i++)
{
count = 1;
for(j=i+1; j<size; j++)
{
// If duplicate element is found
if(arr[i]==arr[j])
{
count++;
// Make sure not to count frequency of same element again
freq[j] = 0;
}
}
// If frequency of current element is not counted
if(freq[i] != 0)
{
freq[i] = count;
}
}
// Print frequency of each element
System.out.print( "Frequency of all elements of array:\n" );
for(i=0; i<size; i++)
{
if(freq[i] != 0)
{
System.out.print(arr[i] + " occurs " + freq[i] + " times \n");
}
}
}
}