# Count frequencies of all elements in array in O(1) extra space and O(n) time in C++

C++Server Side ProgrammingProgramming

We are given with an array of elements ranging from values 1 to n. Some elements are repeated, and some are missing. The goal is to find the frequencies of all elements in O(n) time and O(1) extra space.

## Input

Arr[]= { 1,2,2,3,4,4,4,5 }

## Output

1→ 1, 2 → 2, 3→ 1, 4→ 3, 5→ 5

Explanation − The highest element is 5, the output shows the number of times each element appears in the array.

## Input

Arr[]= { 1,4,4,5,5,5,5 }

## Output

1→ 1, 2 →0, 3→ 0, 4→ 2, 5→ 4

Explanation − The highest element is 5, the output shows the number of times each element appears in the array.

## Approach used in the below program is as follows

• Below program works for arrays with numbers between 1 to 10.

• Function printfrequency(int arr[],int n) takes an array and its size n as input and returns the count of numbers between 1 to 10 present in the array.

• We make arr[i]=arr[i]-1 so that each index stores the frequency of number i, 1 stored at index 0 and so on.

• Using for loop at each frequency arr[arr[i]%10] add 10 to the original value.

• For x times 10 will be added if number i occurs x times in array.

• Now using for loop print frequencies using arr[i]/10 for all elements i+1 at index i.

## Example

Live Demo

#include<bits/stdc++.h>
using namespace std;
void printfrequency(int arr[],int n){
int i=0;
//1 becomes 0, 2 becomes 1 .....10 becomes 9 so arr[i] will have count of i
for ( i =0; i<n; i++)
arr[i] = arr[i]-1;
//as numbers are between 1-10 add 10 to all (num%10 is num itself)
for (i=0; i<n; i++)
arr[arr[i]%10] = arr[arr[i]%10] + 10;
for (i =0; i<10; i++)
cout << i + 1 << " -> " << arr[i]/10 << endl;
}
int main(){
int arr[] = {2, 3, 3, 2, 5, 6, 7, 7, 7, 8, 8, 9, 9};
int n = sizeof(arr)/sizeof(arr);
printfrequency(arr,n);
return 0;
}

## Output

1 -> 0
2 -> 2
3 -> 2
4 -> 0
5 -> 1
6 -> 1
7 -> 3
8 -> 2
9 -> 5
10 -> 0