Count pairs in an array such that frequency of one is at least value of other in C++

C++Server Side ProgrammingProgramming

We are given an array of positive integers. The goal is to find the count of pairs of elements of arr[] such that pairs have elements ( A, B ) where frequency of A is B times and frequency of B is A.

Let us understand with examples.

Input − int arr[] = { 3, 3, 3, 5, 5, 6, 6}

Output − Count of pairs in an array such that frequency of one is at least value of other are − 1

Explanation − The valid pairs in an array where A occurs B times and B occurs A times are (3, 3) as 3 is occurring 3 times in an array. So there is only one valid pair hence the count is 1.

Input − int arr[] = { 3, 3, 3, 3, 3, 5, 5, 5, 6, 6}

Output − Count of pairs in an array such that frequency of one is at least value of other are − 1

Explanation − The valid pairs in an array where A occurs B times and B occurs A times are (3, 3), (5, 5) and (3, 5) as 3 is occurring 5 times and 5 is occurring 3 times in an array. So there are three valid pairs hence the count is 3.

Approach used in the below program is as follows

In the approach we would first create and populate an unordered map containing frequencies of elements of the array. Traverse the unordered_map using for loop. For each element and its frequency, if any frequency is found more, increment count of pairs.

  • Take an array arr[] of integers.

  • Function frequency_other_value(int arr[], int size) takes the array and its size and returns the count of pairs such that pairs are (A,B) where A occurs at-least B times and vice versa.

  • Take the initial count as 0.

  • Take unordered_map<int, int> um for elements of arr[] and their frequencies.

  • Traverse map using for and for each first value of pair start=it.second; (it=iterator), traverse map for frequencies >= start using for loop.

  • Increment count for such pairs.

  • Return count as result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int frequency_other_value(int arr[], int len){
   int count = 0;
   unordered_map<int, int> um;
   for (int i = 0; i < len; ++i){
      um[arr[i]]++;
   }
   for (auto it : um){
      int start = it.first;
      int end = it.second;
      for (int j = 1; j <= end; j++){
         if (um[j] >= start){
            count++;
         }
      }
   }
   return count;
}
int main(){
   int arr[] = { 3, 3, 3, 5, 5, 6, 6};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Count of pairs in an array such that frequency of one is at least value of other are: "<<frequency_other_value(arr, size);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of pairs in an array such that frequency of one is at least value of other are: 1
raja
Updated on 02-Dec-2020 12:26:16

Advertisements