
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count all elements in the array which appears at least K times after their first occurrence in C++
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
#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
Advertisements