Frequency Array

#include using namespace std; const int Nmax=100005; int n, fr[Nmax], a[Nmax]; int main(){ cin>>n; int cnt=0; for(int i=1;i>a[i]; if(fr[a[i]]==0){ cnt++; } fr[a[i]]++; } cout

Mar 21, 2025 - 09:40
 0
Frequency Array
#include
using namespace std;

const int Nmax=100005;
int n, fr[Nmax], a[Nmax];

int main(){
        cin>>n;
        int cnt=0;
        for(int i=1;i<=n;i++){
                cin>>a[i];
                if(fr[a[i]]==0){
                        cnt++;
                }
                fr[a[i]]++;
        }
        cout<

Image description

(I) Crux:

1) This code displays the number of distinct integers in an array of size n,

fr[a[i]] means the number of occurrences of the value at a[i] so if the given value has no previous occurrence i.e is distinct it will counted using cnt++

and then we're updating the frequency of said value using fr[a[i]]++.

2) Like if we enter the value two at a0, so, fr[2] is 0 by default so the if case passes and it's counted as distinct integer.
After that in that iteration fr[2] is set as 1

now if we input the value 2 at any following index, the frequency of 2 , fr[2] is set as 1, so it won't pass if and won't be counted as distinct and we'll update it's frequency again and now set fr[2] = 2.

(II) Hands-on Code Implementation Practice Video(Also available on my YouTube Handle):

1) https://youtu.be/ci_j2Z0RjwE