Given an unsorted array of n integers which can contain integers from 1 to n. Some elements can be repeated multiple times and some other elements can be absent from the array. Count frequency of all elements that are present and print the missing elements.
Examples:
Input: arr[] = {2, 3, 3, 2, 5}
Output: Below are frequencies of all elements
1 -> 0
2 -> 2
3 -> 2
4 -> 0
5 -> 1
Explanation: Frequency of elements 1 is
0, 2 is 2, 3 is 2, 4 is 0 and 5 is 1.
Input: arr[] = {4, 4, 4, 4}
Output: Below are frequencies of all elements
1 -> 0
2 -> 0
3 -> 0
4 -> 4
Explanation: Frequency of elements 1 is
0, 2 is 0, 3 is 0 and 4 is 4.
Simple Solution
- Approach: Create an extra space of size n, as elements of the array is in the range 1 to n. Use the extra space as HashMap. Traverse the array and update the count of the current element. Finally, print the frequencies of the HashMap along with the indices.
- Algorithm:
- Create an extra space of size n (hm), use it as a HashMap.
- Traverse the array from start to end.
- For every element update hm[array[i]-1], i.e. hm[array[i]-1]++
- Run a loop from 0 to n and print hm[array[i]-1] along with the index i
- Implementation:
// C++ program to print frequencies of all array// elements in O(n) extra space and O(n) time#include<bits/stdc++.h>usingnamespacestd;// Function to find counts of all elements present in// arr[0..n-1]. The array elements must be range from// 1 to nvoidfindCounts(int*arr,intn){//Hashmapinthash[n]={0};// Traverse all array elementsinti = 0;while(i<n){//update the frequency of array[i]hash[arr[i]-1]++;//increase the indexi++;}printf("\nBelow are counts of all elements\n");for(inti=0; i<n; i++)printf("%d -> %d\n", i+1, hash[i]);}// Driver program to test above functionintmain(){intarr[] = {2, 3, 3, 2, 5};findCounts(arr,sizeof(arr)/sizeof(arr[0]));intarr1[] = {1};findCounts(arr1,sizeof(arr1)/sizeof(arr1[0]));intarr3[] = {4, 4, 4, 4};findCounts(arr3,sizeof(arr3)/sizeof(arr3[0]));intarr2[] = {1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1};findCounts(arr2,sizeof(arr2)/sizeof(arr2[0]));intarr4[] = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3};findCounts(arr4,sizeof(arr4)/sizeof(arr4[0]));intarr5[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};findCounts(arr5,sizeof(arr5)/sizeof(arr5[0]));intarr6[] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};findCounts(arr6,sizeof(arr6)/sizeof(arr6[0]));return0;}chevron_rightfilter_noneOutput:
Below are counts of all elements 1 -> 0 2 -> 2 3 -> 2 4 -> 0 5 -> 1 Below are counts of all elements 1 -> 1 Below are counts of all elements 1 -> 0 2 -> 0 3 -> 0 4 -> 4 Below are counts of all elements 1 -> 3 2 -> 0 3 -> 2 4 -> 0 5 -> 2 6 -> 0 7 -> 2 8 -> 0 9 -> 2 10 -> 0 11 -> 0 Below are counts of all elements 1 -> 0 2 -> 0 3 -> 11 4 -> 0 5 -> 0 6 -> 0 7 -> 0 8 -> 0 9 -> 0 10 -> 0 11 -> 0 Below are counts of all elements 1 -> 1 2 -> 1 3 -> 1 4 -> 1 5 -> 1 6 -> 1 7 -> 1 8 -> 1 9 -> 1 10 -> 1 11 -> 1 Below are counts of all elements 1 -> 1 2 -> 1 3 -> 1 4 -> 1 5 -> 1 6 -> 1 7 -> 1 8 -> 1 9 -> 1 10 -> 1 11 -> 1
-
Complexity Analysis:
- Time Complexity: O(n).
As a single traversal of array takes O(n) time. - Space Complexity: O(n).
To store all the elements in a HashMap O(n) space is needed.
- Time Complexity: O(n).
Below are two Efficient methods to solve this in O(n) time and O(1) extra space. Both methods modify the given array to achieve O(1) extra space.
Method 2: By making elements negative.
- Approach: The idea is to traverse the given array, use elements as an index and store their counts at the index. Consider the basic approach, a Hashmap of size n is needed and the array is also of size n. So the array can be used as a hashmap, all the elements of the array are from 1 to n, i.e. all are positive elements. So the frequency can be stored as negative. This might lead to a problem. Let i-th element be a then the count should be stored at array[a-1], but when the frequency will be stored the element will be lost. To deal with this problem, first, replace the ith element by array[a-1] and then put -1 at array[a-1]. So our idea is to replace the element by frequency and store the element in the current index and if the element at array[a-1] is already negative, then it is already replaced by a frequency so decrement array[a-1].
- Algorithm:
- Traverse the array from start to end.
- For each element check if the element is less than or equal to zero or not. If negative or zero skip the element as it is freqeuncy.
- If an element (e = array[i] – 1 ) is positive, then check if array[e] is positive or not. If positive then that means it is the first occurrence of e in the array and replace array[i] with array[e], i.earray[i] = array[e] and assign array[e] = -1. If array[e] is negative, then it is not the first occurrence, the update array[e] as array[e]– and update array[i] as array[i] = 0.
- Again, traverse the array and print i+1 as value and array[i] as frequency.
-
Implementation:
C++
// C++ program to print frequencies of all array// elements in O(1) extra space and O(n) time#include<bits/stdc++.h>usingnamespacestd;// Function to find counts of all elements present in// arr[0..n-1]. The array elements must be range from// 1 to nvoidfindCounts(int*arr,intn){// Traverse all array elementsinti = 0;while(i<n){// If this element is already processed,// then nothing to doif(arr[i] <= 0){i++;continue;}// Find index corresponding to this element// For example, index for 5 is 4intelementIndex = arr[i]-1;// If the elementIndex has an element that is not// processed yet, then first store that element// to arr[i] so that we don't lose anything.if(arr[elementIndex] > 0){arr[i] = arr[elementIndex];// After storing arr[elementIndex], change it// to store initial count of 'arr[i]'arr[elementIndex] = -1;}else{// If this is NOT first occurrence of arr[i],// then decrement its count.arr[elementIndex]--;// And initialize arr[i] as 0 means the element// 'i+1' is not seen so fararr[i] = 0;i++;}}printf("\nBelow are counts of all elements\n");for(inti=0; i<n; i++)printf("%d -> %d\n", i+1,abs(arr[i]));}// Driver program to test above functionintmain(){intarr[] = {2, 3, 3, 2, 5};findCounts(arr,sizeof(arr)/sizeof(arr[0]));intarr1[] = {1};findCounts(arr1,sizeof(arr1)/sizeof(arr1[0]));intarr3[] = {4, 4, 4, 4};findCounts(arr3,sizeof(arr3)/sizeof(arr3[0]));intarr2[] = {1, 3, 5, 7, 9, 1, 3, 5, 7, 9, 1};findCounts(arr2,sizeof(arr2)/sizeof(arr2[0]));intarr4[] = {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3};findCounts(arr4,sizeof(arr4)/sizeof(arr4[0]));intarr5[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};findCounts(arr5,sizeof(arr5)/sizeof(arr5[0]));intarr6[] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};findCounts(arr6,sizeof(arr6)/sizeof(arr6[0]));return0;}chevron_rightfilter_noneJava
// Java program to print frequencies of all array// elements in O(1) extra space and O(n) timeclassCountFrequencies{// Function to find counts of all elements present in// arr[0..n-1]. The array elements must be range from// 1 to nvoidfindCounts(intarr[],intn){// Traverse all array elementsinti =0;while(i < n){// If this element is already processed,// then nothing to doif(arr[i] <=0){i++;continue;}// Find index corresponding to this element// For example, index for 5 is 4intelementIndex = arr[i] -1;// If the elementIndex has an element that is not// processed yet, then first store that element// to arr[i] so that we don't lose anything.if(arr[elementIndex] >0){arr[i] = arr[elementIndex];// After storing arr[elementIndex], change it// to store initial count of 'arr[i]'arr[elementIndex] = -1;}else{// If this is NOT first occurrence of arr[i],// then decrement its count.arr[elementIndex]--;// And initialize arr[i] as 0 means the element// 'i+1' is not seen so fararr[i] =0;i++;}}System.out.println("Below are counts of all elements");for(intj =0; j < n; j++)System.out.println(j+1+"->"+ Math.abs(arr[j]));}// Driver program to test above functionspublicstaticvoidmain(String[] args){CountFrequencies count =newCountFrequencies();intarr[] = {2,3,3,2,5};count.findCounts(arr, arr.length);intarr1[] = {1};count.findCounts(arr1, arr1.length);intarr3[] = {4,4,4,4};count.findCounts(arr3, arr3.length);intarr2[] = {1,3,5,7,9,1,3,5,7,9,1};count.findCounts(arr2, arr2.length);intarr4[] = {3,3,3,3,3,3,3,3,3,3,3};count.findCounts(arr4, arr4.length);intarr5[] = {1,2,3,4,5,6,7,8,9,10,11};count.findCounts(arr5, arr5.length);intarr6[] = {11,10,9,8,7,6,5,4,3,2,1};count.findCounts(arr6, arr6.length);}}// This code has been contributed by Mayank Jaiswal(mayank_24)chevron_rightfilter_nonePython3
# Python3 program to print frequencies of all array# elements in O(1) extra space and O(n) time# Function to find counts of all elements present in# arr[0..n-1]. The array elements must be range from# 1 to ndeffindCounts(arr, n):# Traverse all array elementsi=0whilei<n:# If this element is already processed,# then nothing to doifarr[i] <=0:i+=1continue# Find index corresponding to this element# For example, index for 5 is 4elementIndex=arr[i]-1# If the elementIndex has an element that is not# processed yet, then first store that element# to arr[i] so that we don't lose anything.ifarr[elementIndex] >0:arr[i]=arr[elementIndex]# After storing arr[elementIndex], change it# to store initial count of 'arr[i]'arr[elementIndex]=-1else:# If this is NOT first occurrence of arr[i],# then decrement its count.arr[elementIndex]-=1# And initialize arr[i] as 0 means the element# 'i+1' is not seen so fararr[i]=0i+=1print("Below are counts of all elements")foriinrange(0,n):print("%d -> %d"%(i+1,abs(arr[i])))print("")# Driver program to test above functionarr=[2,3,3,2,5]findCounts(arr,len(arr))arr1=[1]findCounts(arr1,len(arr1))arr3=[4,4,4,4]findCounts(arr3,len(arr3))arr2=[1,3,5,7,9,1,3,5,7,9,1]findCounts(arr2,len(arr2))arr4=[3,3,3,3,3,3,3,3,3,3,3]findCounts(arr4,len(arr4))arr5=[1,2,3,4,5,6,7,8,9,10,11]findCounts(arr5,len(arr5))arr6=[11,10,9,8,7,6,5,4,3,2,1]findCounts(arr6,len(arr6))# This code is contributed# by shreyanshi_19chevron_rightfilter_noneC#
// C# program to print frequencies of// all array elements in O(1) extra// space and O(n) timeusingSystem;classGFG{// Function to find counts of all// elements present in arr[0..n-1].// The array elements must be range// from 1 to nvoidfindCounts(int[] arr,intn){// Traverse all array elementsinti = 0;while(i < n){// If this element is already// processed, then nothing to doif(arr[i] <= 0){i++;continue;}// Find index corresponding to// this element. For example,// index for 5 is 4intelementIndex = arr[i] - 1;// If the elementIndex has an element// that is not processed yet, then// first store that element to arr[i]// so that we don't loose anything.if(arr[elementIndex] > 0){arr[i] = arr[elementIndex];// After storing arr[elementIndex],// change it to store initial count// of 'arr[i]'arr[elementIndex] = -1;}else{// If this is NOT first occurrence// of arr[i], then decrement its count.arr[elementIndex]--;// And initialize arr[i] as 0 means// the element 'i+1' is not seen so fararr[i] = 0;i++;}}Console.Write("\nBelow are counts of "+"all elements"+"\n");for(intj = 0; j < n; j++)Console.Write(j + 1 +"->"+Math.Abs(arr[j]) +"\n");}// Driver CodepublicstaticvoidMain(){GFG count =newGFG();int[] arr = {2, 3, 3, 2, 5};count.findCounts(arr, arr.Length);int[] arr1 = {1};count.findCounts(arr1, arr1.Length);int[] arr3 = {4, 4, 4, 4};count.findCounts(arr3, arr3.Length);int[] arr2 = {1, 3, 5, 7, 9, 1,3, 5, 7, 9, 1};count.findCounts(arr2, arr2.Length);int[] arr4 = {3, 3, 3, 3, 3,3, 3, 3, 3, 3, 3};count.findCounts(arr4, arr4.Length);int[] arr5 = {1, 2, 3, 4, 5, 6,7, 8, 9, 10, 11};count.findCounts(arr5, arr5.Length);int[] arr6 = {11, 10, 9, 8, 7, 6,5, 4, 3, 2, 1};count.findCounts(arr6, arr6.Length);}}// This code is contributed by ChitraNayalchevron_rightfilter_noneOutput:
Below are counts of all elements 1 -> 0 2 -> 2 3 -> 2 4 -> 0 5 -> 1 Below are counts of all elements 1 -> 1 Below are counts of all elements 1 -> 0 2 -> 0 3 -> 0 4 -> 4 Below are counts of all elements 1 -> 3 2 -> 0 3 -> 2 4 -> 0 5 -> 2 6 -> 0 7 -> 2 8 -> 0 9 -> 2 10 -> 0 11 -> 0 Below are counts of all elements 1 -> 0 2 -> 0 3 -> 11 4 -> 0 5 -> 0 6 -> 0 7 -> 0 8 -> 0 9 -> 0 10 -> 0 11 -> 0 Below are counts of all elements 1 -> 1 2 -> 1 3 -> 1 4 -> 1 5 -> 1 6 -> 1 7 -> 1 8 -> 1 9 -> 1 10 -> 1 11 -> 1 Below are counts of all elements 1 -> 1 2 -> 1 3 -> 1 4 -> 1 5 -> 1 6 -> 1 7 -> 1 8 -> 1 9 -> 1 10 -> 1 11 -> 1
-
Complexity Analysis:
- Time Complexity: O(n).
As a single traversal of the array takes O(n) time. - Space Complexity: O(1).
Since no extra space is needed.
- Time Complexity: O(n).

Method 3: By adding ‘n’ to keep track of counts.
- Approach: All the array elements are from 1 to n. Reduce every element by 1. The array elements now are in range 0 to n-1 so it can be said that for every index i, floor(array[i]/n) = 0.
So as previously said that the idea is to traverse the given array, use elements as an index and store their counts at the index. Consider the basic approach, a Hashmap of size n is needed and the array is also of size n. So the array can be used as a hashmap but the difference is that instead of replacing elements add n to the array[i]th index.
So after the updadation the array[i]%n will give the ith element and array[i]/n will give the frequency of i+1. - Algorithm:
- Traverse the array from start to end and reduce all the elements by 1.
- Again traverse the array from start to end.
- For each element array[i]%n update array[array[i]%n], i.e array[array[i]%n]++
- Traverse the array from start to end and print i + 1 as value and array[i]/n as frequency.
-
Implementation:
C++
// C++ program to print frequencies of all array// elements in O(1) extra space and O(n) time#include<bits/stdc++.h>usingnamespacestd;// Function to find counts of all elements present in// arr[0..n-1]. The array elements must be range from// 1 to nvoidprintfrequency(intarr[],intn){// Subtract 1 from every element so that the elements// become in range from 0 to n-1for(intj =0; j<n; j++)arr[j] = arr[j]-1;// Use every element arr[i] as index and add 'n' to// element present at arr[i]%n to keep track of count of// occurrences of arr[i]for(inti=0; i<n; i++)arr[arr[i]%n] = arr[arr[i]%n] + n;// To print counts, simply print the number of times n// was added at index corresponding to every elementfor(inti =0; i<n; i++)cout << i + 1 <<" -> "<< arr[i]/n << endl;}// Driver program to test above functionintmain(){intarr[] = {2, 3, 3, 2, 5};intn =sizeof(arr)/sizeof(arr[0]);printfrequency(arr,n);return0;}chevron_rightfilter_noneJava
classCountFrequency{// Function to find counts of all elements present in// arr[0..n-1]. The array elements must be range from// 1 to nvoidprintfrequency(intarr[],intn){// Subtract 1 from every element so that the elements// become in range from 0 to n-1for(intj =0; j < n; j++)arr[j] = arr[j] -1;// Use every element arr[i] as index and add 'n' to// element present at arr[i]%n to keep track of count of// occurrences of arr[i]for(inti =0; i < n; i++)arr[arr[i] % n] = arr[arr[i] % n] + n;// To print counts, simply print the number of times n// was added at index corresponding to every elementfor(inti =0; i < n; i++)System.out.println(i +1+"->"+ arr[i] / n);}// Driver program to test above functionspublicstaticvoidmain(String[] args){CountFrequency count =newCountFrequency();intarr[] = {2,3,3,2,5};intn = arr.length;count.printfrequency(arr, n);}}// This code has been contributed by Mayank Jaiswalchevron_rightfilter_nonePython3
# Python 3 program to print frequencies# of all array elements in O(1) extra# space and O(n) time# Function to find counts of all elements# present in arr[0..n-1]. The array# elements must be range from 1 to ndefprintfrequency(arr, n):# Subtract 1 from every element so that# the elements become in range from 0 to n-1forjinrange(n):arr[j]=arr[j]-1# Use every element arr[i] as index# and add 'n' to element present at# arr[i]%n to keep track of count of# occurrences of arr[i]foriinrange(n):arr[arr[i]%n]=arr[arr[i]%n]+n# To print counts, simply print the# number of times n was added at index# corresponding to every elementforiinrange(n):print(i+1,"->", arr[i]//n)# Driver codearr=[2,3,3,2,5]n=len(arr)printfrequency(arr, n)# This code is contributed# by Shrikant13chevron_rightfilter_noneC#
usingSystem;internalclassCountFrequency{// Function to find counts of all elements present in// arr[0..n-1]. The array elements must be range from// 1 to ninternalvirtualvoidprintfrequency(int[] arr,intn){// Subtract 1 from every element so that the elements// become in range from 0 to n-1for(intj = 0; j < n; j++){arr[j] = arr[j] - 1;}// Use every element arr[i] as index and add 'n' to// element present at arr[i]%n to keep track of count of// occurrences of arr[i]for(inti = 0; i < n; i++){arr[arr[i] % n] = arr[arr[i] % n] + n;}// To print counts, simply print the number of times n// was added at index corresponding to every elementfor(inti = 0; i < n; i++){Console.WriteLine(i + 1 +"->"+ arr[i] / n);}}// Driver program to test above functionspublicstaticvoidMain(string[] args){CountFrequency count =newCountFrequency();int[] arr =newint[] {2, 3, 3, 2, 5};intn = arr.Length;count.printfrequency(arr, n);}}// This code is contributed by Shrikant13chevron_rightfilter_nonePHP
<?php// PHP program to print// frequencies of all// array elements in O(1)// extra space and O(n) time// Function to find counts// of all elements present// in arr[0..n-1]. The array// elements must be range// from 1 to nfunctionprintfrequency($arr,$n){// Subtract 1 from every// element so that the// elements become in// range from 0 to n-1for($j= 0;$j<$n;$j++)$arr[$j] =$arr[$j] - 1;// Use every element arr[i]// as index and add 'n' to// element present at arr[i]%n// to keep track of count of// occurrences of arr[i]for($i= 0;$i<$n;$i++)$arr[$arr[$i] %$n] =$arr[$arr[$i] %$n] +$n;// To print counts, simply// print the number of times// n was added at index// corresponding to every elementfor($i= 0;$i<$n;$i++)echo$i+ 1," -> ",(int)($arr[$i] /$n) ,"\n";}// Driver Code$arr=array(2, 3, 3, 2, 5);$n= sizeof($arr);printfrequency($arr,$n);// This code is contributed by ajit?>chevron_rightfilter_none
Output:1 -> 0 2 -> 2 3 -> 2 4 -> 0 5 -> 1
-
Complexity Analysis:
- Time Complexity: O(n).
Only two traversals of the array are needed and single traversal of the array takes O(n) time. - Space Complexity: O(1).
Since, no extra space is needed.
- Time Complexity: O(n).

Thanks to Vivek Kumar for suggesting this solution in a comment below.
This article is contributed by Shubham Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Duplicates in an array in O(n) time and by using O(1) extra space | Set-3
- Find duplicates in O(n) time and O(1) extra space | Set 1
- Count frequencies of all elements in array in Python using collections module
- Design a stack that supports getMin() in O(1) time and O(1) extra space
- Find the maximum repeating number in O(n) time and O(1) extra space
- Rearrange positive and negative numbers in O(n) time and O(1) extra space
- Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers)
- k smallest elements in same order using O(1) extra space
- Move all negative elements to end in order with extra space allowed
- Duplicates in an array in O(n) and by using O(1) extra space | Set-2
- Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space
- Shuffle array {a1, a2, .. an, b1, b2, .. bn} as {a1, b1, a2, b2, a3, b3, ……, an, bn} without using extra space
- Rearrange an array in maximum minimum form | Set 2 (O(1) extra space)
- Rearrange array in alternating positive & negative items with O(1) extra space | Set 2
- Rearrange array in alternating positive & negative items with O(1) extra space | Set 1
- Count of subarrays of size K with elements having even frequencies
- Elements of first array that have more frequencies
- Array elements with prime frequencies
- Counting frequencies of array elements
- Find the frequencies of all duplicates elements in the array

