Cumulative frequency of count of each element in an unsorted array
Last Updated : 14 Aug, 2024
Given an unsorted array. The task is to calculate the cumulative frequency of each element of the array using a count array.
Examples:
Input : arr[] = [1, 2, 2, 1, 3, 4]
Output :1->2
2->4
3->5
4->6
Input : arr[] = [1, 1, 1, 2, 2, 2]
Output :1->3
2->6
A simple solution is to use two nested loops. The outer loop picks an element from left to right that is not visited. The inner loop counts its occurrences and marks occurrences as visited. The time complexity of this solution is O(n*n) and the auxiliary space required is O(n).
A better solution is to use sorting. We sort the array so that the same elements come together. After sorting, we linearly traverse elements and count their frequencies.
An efficient solution is to use hashing. Insert the element and its frequency in a set of pairs. As the set stores unique values in a sorted order, it will store all the elements with their frequencies in a sorted order. Iterate in the set and print the frequencies by adding the previous ones at every step.
Below is the implementation of the above approach:
C++ #include <bits/stdc++.h> using namespace std; // Function to print the cumulative frequency according to // the order given void countFreq(int a[], int n) { // Declaring a map so values get inserted in a sorted // manner map<int, int> m; // Inserting values into the map for (int i = 0; i < n; i++) { m[a[i]]++; } // Variable to store the count of previous number // cumulative frequency int cumul = 0; for (auto v : m) { cout << v.first << " " << v.second + cumul << endl; cumul += v.second; } } int main() { int arr[] = { 1, 3, 2, 4, 2, 1 }; int n = sizeof(arr) / sizeof(arr[0]); countFreq(arr, n); return 0; } // This code is contributed by Vinayak Pareek (Kargil)
Java // Java program to count cumulative // frequencies of elements in an unsorted array. import java.util.*; class GFG { static void countFreq(int[] a, int n) { // Insert elements and their // frequencies in hash map. HashMap<Integer, Integer> hm = new HashMap<>(); for (int i = 0; i < n; i++) hm.put(a[i], hm.get(a[i]) == null ? 1 : hm.get(a[i]) + 1); // Declare a Map SortedMap<Integer, Integer> st = new TreeMap<>(); // insert the element and // and insert its frequency in a set for (HashMap.Entry<Integer, Integer> x : hm.entrySet()) { st.put(x.getKey(), x.getValue()); } int cumul = 0; // iterate the set and print the // cumulative frequency for (SortedMap.Entry<Integer, Integer> x : st.entrySet()) { cumul += x.getValue(); System.out.println(x.getKey() + " " + cumul); } } // Driver Code public static void main(String[] args) { int[] a = { 1, 3, 2, 4, 2, 1 }; int n = a.length; countFreq(a, n); } } // This code is contributed by // sanjeev2552
Python3 # Python3 program to count cumulative # frequencies of elements in an unsorted array. def countFreq(a, n): # Insert elements and their # frequencies in hash map. hm = {} for i in range(0, n): hm[a[i]] = hm.get(a[i], 0) + 1 # Declare a set st = set() # Insert the element and # its frequency in a set for x in hm: st.add((x, hm[x])) cumul = 0 # Iterate the set and print # the cumulative frequency for x in sorted(st): cumul += x[1] print(x[0], cumul) # Driver Code if __name__ == "__main__": a = [1, 3, 2, 4, 2, 1] n = len(a) countFreq(a, n) # This code is contributed by Rituraj Jain
C# // C# program to count cumulative // frequencies of elements in an // unsorted array. using System; using System.Collections.Generic; using System.Linq; class GFG{ static void countFreq(int[] a, int n) { // Insert elements and their // frequencies in hash map. Dictionary<int, int> hm = new Dictionary<int, int>(); for(int i = 0; i < n; i++) { if (hm.ContainsKey(a[i])) { hm[a[i]]++; } else { hm[a[i]] = 1; } } int cumul = 0; // Iterate the set and print the // cumulative frequency foreach(KeyValuePair<int, int> x in hm.OrderBy(key => key.Key)) { cumul += x.Value; Console.Write(x.Key + " " + cumul + "\n"); } } // Driver Code public static void Main(string[] args) { int[] a = { 1, 3, 2, 4, 2, 1 }; int n = a.Length; countFreq(a, n); } } // This code is contributed by rutvik_56
JavaScript <script> // Javascript program to count cumulative // frequencies of elements in an unsorted array. function countFreq(a,n) { // Insert elements and their // frequencies in hash map. let hm = new Map(); for (let i = 0; i < n; i++) hm.set(a[i], hm.get(a[i]) == null ? 1 : hm.get(a[i]) + 1); // Declare a Map let st = new Set(); // insert the element and // and insert its frequency in a set for (let [key, value] of hm.entries()) { st.add([key, value]); } st=[...st.entries()].sort() let cumul = 0; // iterate the set and print the // cumulative frequency for (let [key, value] of st.entries()) { cumul += value[1][1]; document.write(value[1][0] + " " + cumul+"<br>"); } } // Driver Code let a=[1, 3, 2, 4, 2, 1]; let n = a.length; countFreq(a, n); // This code is contributed by unknown2108 </script>
Time Complexity: O(n log n), where n is the size of the given array
Auxiliary Space: O(n), as extra space of size n is used to create a map
What if we need frequencies of elements according to the order of the first occurrence?
For example, an array [2, 4, 1, 2, 1, 3, 4], the frequency of 2 should be printed first, then of 4, then 1, and finally 3.
Approach: Hash the count of occurrences of an element. Traverse in the array and print the cumulative frequency. Once the element and its cumulative frequency has been printed, hash the occurrence of that element as 0 so that it not printed again if it appears in the latter half of array while traversal.
Below is the implementation of the above approach:
C++ // C++ program to print the cumulative frequency // according to the order given #include <bits/stdc++.h> using namespace std; // Function to print the cumulative frequency // according to the order given void countFreq(int a[], int n) { // Insert elements and their // frequencies in hash map. unordered_map<int, int> hm; for (int i=0; i<n; i++) hm[a[i]]++; int cumul = 0; // traverse in the array for(int i=0;i<n;i++) { // add the frequencies cumul += hm[a[i]]; // if the element has not been // visited previously if(hm[a[i]]) { cout << a[i] << "->" << cumul << endl; } // mark the hash 0 // as the element's cumulative frequency // has been printed hm[a[i]]=0; } } // Driver Code int main() { int a[] = {1, 3, 2, 4, 2, 1}; int n = sizeof(a)/sizeof(a[0]); countFreq(a, n); return 0; }
Java // Java program to print the cumulative frequency // according to the order given class GFG { // Function to print the cumulative frequency // according to the order given static void countFreq(int a[], int n) { // Insert elements and their // frequencies in hash map. int hm[] = new int[n]; for (int i = 0; i < n; i++) hm[a[i]]++; int cumul = 0; // traverse in the array for(int i = 0; i < n; i++) { // add the frequencies cumul += hm[a[i]]; // if the element has not been // visited previously if(hm[a[i]] != 0) { System.out.println(a[i] + "->" + cumul); } // mark the hash 0 // as the element's cumulative frequency // has been printed hm[a[i]] = 0; } } // Driver Code public static void main(String[] args) { int a[] = {1, 3, 2, 4, 2, 1}; int n = a.length; countFreq(a, n); } } // This code has been contributed by 29AjayKumar
Python3 # Python3 program to print the cumulative # frequency according to the order given # Function to print the cumulative frequency # according to the order given def countFreq(a, n): # Insert elements and their # frequencies in hash map. hm = dict() for i in range(n): hm[a[i]] = hm.get(a[i], 0) + 1 cumul = 0 # traverse in the array for i in range(n): # add the frequencies cumul += hm[a[i]] # if the element has not been # visited previously if(hm[a[i]] > 0): print(a[i], "->", cumul) # mark the hash 0 # as the element's cumulative # frequency has been printed hm[a[i]] = 0 # Driver Code a = [1, 3, 2, 4, 2, 1] n = len(a) countFreq(a, n) # This code is contributed by mohit kumar
C# // C# program to print the cumulative frequency // according to the order given using System; class GFG { // Function to print the cumulative frequency // according to the order given static void countFreq(int []a, int n) { // Insert elements and their // frequencies in hash map. int []hm = new int[n]; for (int i = 0; i < n; i++) hm[a[i]]++; int cumul = 0; // traverse in the array for(int i = 0; i < n; i++) { // add the frequencies cumul += hm[a[i]]; // if the element has not been // visited previously if(hm[a[i]] != 0) { Console.WriteLine(a[i] + "->" + cumul); } // mark the hash 0 // as the element's cumulative frequency // has been printed hm[a[i]] = 0; } } // Driver Code public static void Main(String[] args) { int []a = {1, 3, 2, 4, 2, 1}; int n = a.Length; countFreq(a, n); } } /* This code contributed by PrinciRaj1992 */
JavaScript <script> // Javascript program to print the cumulative frequency // according to the order given // Function to print the cumulative frequency // according to the order given function countFreq(a,n) { // Insert elements and their // frequencies in hash map. let hm = new Array(n); for(let i=0;i<hm.length;i++) { hm[i]=0; } for (let i = 0; i < n; i++) hm[a[i]]++; let cumul = 0; // traverse in the array for(let i = 0; i < n; i++) { // add the frequencies cumul += hm[a[i]]; // if the element has not been // visited previously if(hm[a[i]] != 0) { document.write(a[i] + "->" + cumul+"<br>"); } // mark the hash 0 // as the element's cumulative frequency // has been printed hm[a[i]] = 0; } } // Driver Code let a=[1, 3, 2, 4, 2, 1]; let n = a.length; countFreq(a, n); // This code is contributed by patel2127 </script>
Output1->2 3->3 2->5 4->6
Time Complexity: O(n), where n is the size of the given array
Auxiliary Space: O(n), as extra space of size n is used to create a map
Similar Reads
Find the frequency of each element in a sorted array
Given a sorted array, arr[] consisting of N integers, the task is to find the frequencies of each array element. Examples: Input: arr[] = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10} Output: Frequency of 1 is: 3 Frequency of 2 is: 1 Frequency of 3 is: 2 Frequency of 5 is: 2 Frequency of 8 is: 3 Frequ
10 min read
Count of larger elements on right side of each element in an array
Given an array arr[] consisting of N integers, the task is to count the number of greater elements on the right side of each array element. Examples: Input: arr[] = {3, 7, 1, 5, 9, 2} Output: {3, 1, 3, 1, 0, 0} Explanation: For arr[0], the elements greater than it on the right are {7, 5, 9}. For arr
15+ min read
Count distinct elements from a range of a sorted sequence from a given frequency array
Given two integers L and R and an array arr[] consisting of N positive integers( 1-based indexing ) such that the frequency of ith element of a sorted sequence, say A[], is arr[i]. The task is to find the number of distinct elements from the range [L, R] in the sequence A[]. Examples: Input: arr[] =
13 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 of pairs having each element equal to index of the other from an Array
Given an integer N and an array arr[] that contains elements in the range [1, N], the task is to find the count of all pairs (arr[i], arr[j]) such that i < j and i == arr[j] and j == arr[i]. Examples: Input: N = 4, arr[] = {2, 1, 4, 3} Output: 2 Explanation: All possible pairs are {1, 2} and {3,
6 min read
Total count of elements having frequency one in each Subarray
Given an array arr[] of length N, the task is to find the total number of elements that has frequency 1 in a subarray of the given array. Examples: Input: N = 3, arr[ ] = {2, 4, 2}Output: 8Explanation: All possible subarrays are {2}: elements with frequency one = 1.{4}: elements with frequency one =
13 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
Counting frequencies of array elements
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 1Input : 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.
15+ min read
Count of greater elements for each element in the Array
Given an array arr of integers of size N, the task is to find, for every element, the number of elements that are greater than it.Examples: Input: arr[] = {4, 6, 2, 1, 8, 7} Output: {3, 2, 4, 5, 0, 1}Input: arr[] = {2, 3, 4, 5, 6, 7, 8} Output: {6, 5, 4, 3, 2, 1, 0} Approach: Store the frequencies o
5 min read
Count of right shifts for each array element to be in its sorted position
Given an array arr[] of size N that contains elements from the range [1, N], the task is to calculate the number of right shifts required for each element to reach its respective position if the array was sorted.Examples: Input: arr[] = {1, 4, 3, 2, 5}, N = 5 Output: 0 2 0 3 0 Explanation: The sorte
5 min read