Count all elements in the array which appears at least K times after their first occurrence in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find the number of elements in the array which appears at least K times after their first occurrence.

For this we will be provided with an integer array and a value k. Our task is to count all the elements occurring k times among the elements after the element in consideration.

Example

 Live Demo

#include <iostream>
#include <map>
using namespace std;
//returning the count of elements
int calc_count(int n, int arr[], int k){
   int cnt, ans = 0;
   //avoiding duplicates
   map<int, bool> hash;
   for (int i = 0; i < n; i++) {
      cnt = 0;
      if (hash[arr[i]] == true)
         continue;
      hash[arr[i]] = true;
      for (int j = i + 1; j < n; j++) {
         if (arr[j] == arr[i])
            cnt++;
         //if k elements are present
         if (cnt >= k)
            break;
      }
      if (cnt >= k)
         ans++;
   }
   return ans;
}
int main(){
   int arr[] = { 1, 2, 1, 3 };
   int n = sizeof(arr) / sizeof(arr[0]);
   int k = 1;
   cout << calc_count(n, arr, k);
   return 0;
}

Output

1
raja
Published on 05-Feb-2020 12:14:29
Advertisements