Count the elements having frequency equals to its value | Set 2

Given an array of integers arr[] of size N, the task is to count all the elements of the array which have a frequency equals to its value.

Examples:

Input: arr[] = {3, 2, 2, 3, 4, 3}
Output: 2
Explanation :
Frequency of element 2 is 2
Frequency of element 3 is 3
Frequency of element 4 is 1
2 and 3 are elements which have same frequency as it’s value
Input: arr[] = {1, 2, 3, 4, 5, 6}
Output: 1

Approach :
Follow the steps below to solve the problem:

  1. Store the frequencies of every array element with value less than equal to array size in a Hashmap.
  2. The reason for above step is that the frequency of an element can be atmost equal to the size of the given array. Hence, there is no need to store frequency of an element, whose value is greater than given array size.
  3. Count the integers having frequencies equal to its value.
  4. Print the final count.

Below is the implementation of the above approach:



C++

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <bits/stdc++.h>
using namespace std;
  
// Function to find the integer
// which has a frequency in the
// array equal to its value.
void solve(int arr[], int n)
{
    // Store frequency of array
    // elements
    map<int, int> freq;
  
    for (int i = 0; i < n; i++) {
  
        // Store the frequency
        // only if arr[i]<=n
        if (arr[i] <= n)
            freq[arr[i]]++;
    }
  
    // Initially the count is zero
    int count = 0;
  
    for (int i = 1; i <= n; i++) {
        // If the freq[i] is equal
        // to i, then increment
        // the count by 1
        if (i == freq[i]) {
            count++;
        }
    }
  
    // Print the final count
    cout << count << "\n";
}
  
// Driver Program
int main()
{
    int arr[] = { 3, 1, 1, 3, 2, 2, 3 };
    int N = sizeof(arr) / sizeof(arr[0]);
  
    solve(arr, N);
    return 0;
}

chevron_right


Output:

2

Time Complexity: O(N)
Auxillary Space Complexity: O(N)

Refer to the previous post for O(N*log(N)) approach.

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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.