Counting frequencies of array elements
Last Updated : 03 Oct, 2023
Given an array which may contain duplicates, print all elements and their frequencies.
Examples:
Input : arr[] = {10, 20, 20, 10, 10, 20, 5, 20}
Output : 10 3
20 4
5 1
Input : arr[] = {10, 20, 20}
Output : 10 1
20 2
A simple solution is to run two loops. For every item count number of times, it occurs. To avoid duplicate printing, keep track of processed items.
Implementation:
C++
#include <bits/stdc++.h> using namespace std; void countFreq( int arr[], int n) { vector< bool > visited(n, false ); for ( int i = 0; i < n; i++) { if (visited[i] == true ) continue ; int count = 1; for ( int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true ; count++; } } cout << arr[i] << " " << count << endl; } } int main() { int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof (arr) / sizeof (arr[0]); countFreq(arr, n); return 0; } |
Java
import java.util.Arrays; class GFG { public static void countFreq( int arr[], int n) { boolean visited[] = new boolean [n]; Arrays.fill(visited, false ); for ( int i = 0 ; i < n; i++) { if (visited[i] == true ) continue ; 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] + " " + count); } } public static void main(String []args) { int arr[] = new int []{ 10 , 20 , 20 , 10 , 10 , 20 , 5 , 20 }; int n = arr.length; countFreq(arr, n); } } |
Python3
def countFreq(arr, n): visited = [ False for i in range (n)] for i in range (n): if (visited[i] = = True ): continue count = 1 for j in range (i + 1 , n, 1 ): if (arr[i] = = arr[j]): visited[j] = True count + = 1 print (arr[i], count) if __name__ = = '__main__' : arr = [ 10 , 20 , 20 , 10 , 10 , 20 , 5 , 20 ] n = len (arr) countFreq(arr, n) |
C#
using System; class GFG { public static void countFreq( int []arr, int n) { bool []visited = new bool [n]; for ( int i = 0; i < n; i++) { if (visited[i] == true ) continue ; int count = 1; for ( int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true ; count++; } } Console.WriteLine(arr[i] + " " + count); } } public static void Main(String []args) { int []arr = new int []{ 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.Length; countFreq(arr, n); } } |
Javascript
<script> function countFreq(arr, n) { let visited = Array.from({length: n}, (_, i) => false ); for (let i = 0; i < n; i++) { if (visited[i] == true ) continue ; let count = 1; for (let j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { visited[j] = true ; count++; } } document.write(arr[i] + " " + count + "<br/>" ); } } let arr = [ 10, 20, 20, 10, 10, 20, 5, 20 ]; let n = arr.length; countFreq(arr, n); </script> |
Complexity Analysis:
- Time Complexity : O(n2)
- Auxiliary Space : O(n)
An efficient solution is to use hashing.
Implementation:
C++
#include <bits/stdc++.h> using namespace std; void countFreq( int arr[], int n) { unordered_map< int , int > mp; for ( int i = 0; i < n; i++) mp[arr[i]]++; for ( auto x : mp) cout << x.first << " " << x.second << endl; } int main() { int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof (arr) / sizeof (arr[0]); countFreq(arr, n); return 0; } |
Java
import java.util.*; class GFG { static void countFreq( int arr[], int n) { Map<Integer, Integer> mp = new HashMap<>(); 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 ); } } for (Map.Entry<Integer, Integer> entry : mp.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } public static void main(String args[]) { int arr[] = { 10 , 20 , 20 , 10 , 10 , 20 , 5 , 20 }; int n = arr.length; countFreq(arr, n); } } |
Python3
def countFreq(arr, n): mp = dict () for i in range (n): if arr[i] in mp.keys(): mp[arr[i]] + = 1 else : mp[arr[i]] = 1 for x in mp: print (x, " " , mp[x]) arr = [ 10 , 20 , 20 , 10 , 10 , 20 , 5 , 20 ] n = len (arr) countFreq(arr, n) |
C#
using System; using System.Collections.Generic; class GFG { static void countFreq( int []arr, int n) { Dictionary< int , int > mp = new Dictionary< int , int >(); for ( int i = 0; i < n; i++) { if (mp.ContainsKey(arr[i])) { var val = mp[arr[i]]; mp.Remove(arr[i]); mp.Add(arr[i], val + 1); } else { mp.Add(arr[i], 1); } } foreach (KeyValuePair< int , int > entry in mp) { Console.WriteLine(entry.Key + " " + entry.Value); } } public static void Main(String []args) { int []arr = {10, 20, 20, 10, 10, 20, 5, 20}; int n = arr.Length; countFreq(arr, n); } } |
Javascript
<script> function countFreq(arr, n) { const map ={} for (let i = 0; i < n; i++) { if (map[arr[i]){ map[arr[i]]+=1 } else { map[arr[i]] =1 } } console.log(map) } var arr = [10, 20, 20, 10, 10, 20, 5, 20]; var n = arr.length; countFreq(arr, n); </script> |
Complexity Analysis:
- Time Complexity : O(n)
- Auxiliary Space : O(n)
In the above efficient solution, how to print elements in same order as they appear in input?
Implementation:
C++
#include <bits/stdc++.h> using namespace std; void countFreq( int arr[], int n) { unordered_map< int , int > mp; for ( int i = 0; i < n; i++) mp[arr[i]]++; for ( int i = 0; i < n; i++) { if (mp[arr[i]] != -1) { cout << arr[i] << " " << mp[arr[i]] << endl; mp[arr[i]] = -1; } } } int main() { int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof (arr) / sizeof (arr[0]); countFreq(arr, n); return 0; } |
Java
import java.util.*; class GFG { static void countFreq( int arr[], int n) { Map<Integer, Integer> mp = new HashMap<>(); for ( int i = 0 ; i < n; i++) { mp.put(arr[i], mp.get(arr[i]) == null ? 1 : mp.get(arr[i]) + 1 ); } for ( int i = 0 ; i < n; i++) { if (mp.get(arr[i]) != - 1 ) { System.out.println(arr[i] + " " + mp.get(arr[i])); mp.put(arr[i], - 1 ); } } } public static void main(String[] args) { int arr[] = { 10 , 20 , 20 , 10 , 10 , 20 , 5 , 20 }; int n = arr.length; countFreq(arr, n); } } |
Python3
def countFreq(arr, n): mp = {} for i in range (n): if arr[i] not in mp: mp[arr[i]] = 0 mp[arr[i]] + = 1 for i in range (n): if (mp[arr[i]] ! = - 1 ): print (arr[i],mp[arr[i]]) mp[arr[i]] = - 1 arr = [ 10 , 20 , 20 , 10 , 10 , 20 , 5 , 20 ] n = len (arr) countFreq(arr, n) |
C#
using System; using System.Collections.Generic; class GFG { static void countFreq( int []arr, int n) { Dictionary< int , int > mp = new Dictionary< int , int >(); for ( int i = 0 ; i < n; i++) { if (mp.ContainsKey(arr[i])) { var val = mp[arr[i]]; mp.Remove(arr[i]); mp.Add(arr[i], val + 1); } else { mp.Add(arr[i], 1); } } for ( int i = 0; i < n; i++) { if (mp.ContainsKey(arr[i]) && mp[arr[i]] != -1) { Console.WriteLine(arr[i] + " " + mp[arr[i]]); mp.Remove(arr[i]); mp.Add(arr[i], -1); } } } public static void Main(String[] args) { int []arr = {10, 20, 20, 10, 10, 20, 5, 20}; int n = arr.Length; countFreq(arr, n); } } |
Javascript
<script> function countFreq(arr, n) { var mp = new Map(); for ( var i = 0; i < n; i++) { if (mp.has(arr[i])) mp.set(arr[i], mp.get(arr[i])+1) else mp.set(arr[i], 1) } for ( var i = 0; i < n; i++) { if (mp.get(arr[i]) != -1) { document.write( arr[i] + " " + mp.get(arr[i]) + "<br>" ); mp.set(arr[i], -1); } } } var arr = [10, 20, 20, 10, 10, 20, 5, 20]; var n = arr.length; countFreq(arr, n); </script> |
Complexity Analysis:
- Time Complexity : O(n)
- Auxiliary Space : O(n)
This problem can be solved in Java using Hashmap. Below is the program.
Implementation:
C++
#include <bits/stdc++.h> using namespace std; void frequencyNumber( int arr[], int size) { unordered_map< int , int >freqMap; for ( int i=0;i<size;i++) { freqMap[arr[i]]++; } for ( auto it : freqMap) { cout<<it.first<< " " <<it.second<<endl; } } int main() { int arr[] = {10, 20, 20, 10, 10, 20, 5, 20}; int size = sizeof (arr)/ sizeof (arr[0]); frequencyNumber(arr,size); } |
Java
import java.io.*; import java.util.*; class OccurenceOfNumberInArray { static void frequencyNumber( int arr[], int size) { HashMap<Integer, Integer> freqMap = new HashMap<Integer, Integer>(); for ( int i= 0 ;i<size;i++) { if (freqMap.containsKey(arr[i])) { freqMap.put(arr[i], freqMap.get(arr[i]) + 1 ); } else { freqMap.put(arr[i], 1 ); } } for (Map.Entry entry : freqMap.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } } public static void main(String[] args) { int arr[] = { 10 , 20 , 20 , 10 , 10 , 20 , 5 , 20 }; int size = arr.length; frequencyNumber(arr,size); } } |
Python3
def frequencyNumber(arr,size): freqMap = {} for i in range (size): if (arr[i] in freqMap): freqMap[arr[i]] = freqMap[arr[i]] + 1 else : freqMap[arr[i]] = 1 for key, value in freqMap.items(): print (f "{key} {value}" ) arr = [ 10 , 20 , 20 , 10 , 10 , 20 , 5 , 20 ] size = len (arr) frequencyNumber(arr,size) |
C#
using System; using System.Collections.Generic; class GFG { static void frequencyNumber( int []arr, int size) { Dictionary< int , int > freqMap = new Dictionary< int , int >(); for ( int i = 0; i < size; i++){ if (freqMap.ContainsKey(arr[i])) { var val = freqMap[arr[i]]; freqMap.Remove(arr[i]); freqMap.Add(arr[i], val + 1); } else { freqMap.Add(arr[i], 1); } } foreach (KeyValuePair< int , int > entry in freqMap) { Console.WriteLine(entry.Key + " " + entry.Value); } } public static void Main(String []args) { int []arr = {10, 20, 20, 10, 10, 20, 5, 20}; int size = arr.Length; frequencyNumber(arr,size); } } |
Javascript
<script> function frequencyNumber(arr,size) { let freqMap = new Map(); for (let i=0;i<size;i++) { if (freqMap.has(arr[i])) { freqMap.set(arr[i], freqMap.get(arr[i]) + 1); } else { freqMap.set(arr[i], 1); } } for (let [key, value] of freqMap.entries()) { document.write(key + " " + value+ "<br>" ); } } let arr=[10, 20, 20, 10, 10, 20, 5, 20]; let size = arr.length; frequencyNumber(arr,size); </script> |
Complexity Analysis:
- Time Complexity: O(n) since using a single loop to track frequency
- Auxiliary Space: O(n) for hashmap.
Another Efficient Solution (Space optimization): we can find frequency of array elements using Binary search function . First we will sort the array for binary search . Our frequency of element will be ‘(last occ – first occ)+1’ of a element in a array .
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h> using namespace std; void countFreq( int arr[], int n) { sort(arr,arr+n); for ( int i = 0 ; i < n ;i++) { int first_index = lower_bound(arr,arr+n,arr[i])- arr; int last_index = upper_bound(arr,arr+n,arr[i])- arr-1; i=last_index; int fre=last_index-first_index+1; cout << arr[i] << " " <<fre <<endl; } } int main() { int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof (arr) / sizeof (arr[0]); countFreq(arr, n); return 0; } |
Java
import java.io.*; import java.util.*; class OccurenceOfNumberInArray { public static void countFreq( int [] arr, int n) { Arrays.sort(arr); for ( int i = 0 ; i < n; i++) { int first_index = Arrays.binarySearch(arr, arr[i]); int last_index = Arrays.binarySearch(arr, arr[i]); while (first_index > 0 && arr[first_index - 1 ] == arr[i]) { first_index--; } while (last_index < n - 1 && arr[last_index + 1 ] == arr[i]) { last_index++; } i = last_index; int fre = last_index - first_index + 1 ; System.out.println(arr[i] + " " + fre); } } public static void main(String[] args) { int arr[] = { 10 , 20 , 20 , 10 , 10 , 20 , 5 , 20 }; int size = arr.length; countFreq(arr,size); } } |
Python3
from bisect import bisect_left, bisect_right def countFreq(arr, n): arr.sort() i = 0 while i < n: first_index = bisect_left(arr, arr[i]) last_index = bisect_right(arr, arr[i]) - 1 i = last_index + 1 fre = last_index - first_index + 1 print (arr[i - 1 ], fre) arr = [ 10 , 20 , 20 , 10 , 10 , 20 , 5 , 20 ] n = len (arr) countFreq(arr, n) |
C#
using System; public class GFG { public static void countFreq( int [] arr, int n) { Array.Sort(arr); for ( int i = 0; i < n; i++) { int first_index = Array.IndexOf(arr, arr[i]); int last_index = Array.LastIndexOf(arr, arr[i]); int fre = last_index - first_index + 1; Console.WriteLine(arr[i] + " " + fre); i = last_index; } } static public void Main () { int [] arr = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.Length; countFreq(arr, n); } } |
Javascript
function countFreq(arr,n) { arr.sort((a, b) => a - b); let i = 0; while (i < n) { const first_index = arr.indexOf(arr[i]); const last_index = arr.lastIndexOf(arr[i]); i = last_index; const fre = last_index - first_index + 1; console.log(arr[i], fre); i++; } } const arr = [ 10, 20, 20, 10, 10, 20, 5, 20 ]; countFreq(arr,arr.length); |
Time Complexity: O(n*log2n) , where O(log2n) time for binary search function .
Auxiliary Space: O(1)
Similar Reads
JavaScript - Counting Frequencies of Array Elements
Here are the various approaches to count the frequencies of array elements in JavaScript. Using an Object (Simple and Efficient)This is the most common approach for counting frequency in an array. Each array element becomes a key in the object, and its value is incremented as the element appears. [G
2 min read
Frequency of an element in an array
Given an array, a[], and an element x, find a number of occurrences of x in a[]. Examples: Input : a[] = {0, 5, 5, 5, 4} x = 5Output : 3Input : a[] = {1, 2, 3} x = 4Output : 0 Unsorted ArrayThe idea is simple, we initialize count as 0. We traverse the array in a linear fashion. For every element tha
9 min read
Count frequency of digit K in given Array
Given an array arr[] of integers of size N and a single digit integer K. The task is to find the total count of occurrences of the digit K in the array Examples: Input: arr[] = {15, 66, 26, 91}, K = 6Output: 3Explanation: Occurrences of 6 in each array elements are: 0, 2, 1, 0 respectively.Therefore
5 min read
Count Distinct ( Unique ) elements in an array
Given an array arr[] of length N, The task is to count all distinct elements in arr[]. Examples: Input: arr[] = {10, 20, 20, 10, 30, 10}Output: 3Explanation: There are three distinct elements 10, 20, and 30. Input: arr[] = {10, 20, 20, 10, 20}Output: 2 Naïve Approach: Create a count variable and ru
15 min read
Range Queries for Frequencies of array elements
Given an array of n non-negative integers. The task is to find frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type. Examples: Input : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; lef
13 min read
Count of Subsequences with distinct elements
Given an array arr[] (1<=a[i]<=1e9) containing N (1<=N<=1e5) elements, the task is to find the total number of subsequences such that all elements in that subsequences are distinct. Since the answer can be very large print and modulo 1e9+7. Examples: Input: arr[] = [1, 1, 2, 2]Output: 8E
5 min read
Count distinct elements in an array in Python
Given an unsorted array, count all distinct elements in it. Examples: Input : arr[] = {10, 20, 20, 10, 30, 10} Output : 3 Input : arr[] = {10, 20, 20, 10, 20} Output : 2 We have existing solution for this article. We can solve this problem in Python3 using Counter method. Approach#1: Using Set() Thi
2 min read
Count Subsequences with ordered integers in Array
Given an array nums[] of N positive integers, the task is to find the number of subsequences that can be created from the array where each subsequence contains all integers from 1 to its size in any order. If two subsequences have different chosen indices, then they are considered different. Example
7 min read
Count of smaller or equal elements in sorted array
Given a sorted array of size n. Find a number of elements that are less than or equal to a given element. Examples: Input : arr[] = {1, 2, 4, 5, 8, 10} key = 9 Output : 5 Elements less than or equal to 9 are 1, 2, 4, 5, 8 therefore result will be 5. Input : arr[] = {1, 2, 2, 2, 5, 7, 9} key = 2 Outp
15+ min read
Count pairs formed by distinct element sub-arrays
Given an array, count number of pairs that can be formed from all possible contiguous sub-arrays containing distinct numbers. The array contains positive numbers between 0 to n-1 where n is the size of the array. Examples: Input: [1, 4, 2, 4, 3, 2] Output: 8 The subarrays with distinct elements are
7 min read