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

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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);
int k = 1;
cout << calc_count(n, arr, k);
return 0;
}

## Output

1