# Array range queries for elements with frequency same as value in C Program?

CServer Side ProgrammingProgramming

Here we will see one interesting problem. We have one array with N elements. We have to perform one query Q as follows −

The Q(start, end) indicates that number of times a number ‘p’ is occurred exactly ‘p’ number of times from start to end.

So if the array is like: {1, 5, 2, 3, 1, 3, 5, 7, 3, 9, 8}, and queries are −

Q(1, 8) − Here the 1 is present once, and 3 is present 3 times. So the answer is 2

Q(0, 2) − Here the 1 is present once. So the answer is 1

## Algorithm

query(s, e) −

Begin
get the elements and count the frequency of each element ‘e’ into one map
count := count + 1
for each key-value pair p, do
if p.key = p.value, then
count := count + 1
done
return count;
End

## Example

#include <iostream>
#include <map>
using namespace std;
int query(int start, int end, int arr[]) {
map<int, int> freq;
for (int i = start; i <= end; i++) //get element and store frequency
freq[arr[i]]++;
int count = 0;
for (auto x : freq)
if (x.first == x.second) //when the frequencies are same, increase count count++;
return count;
}
int main() {
int A[] = {1, 5, 2, 3, 1, 3, 5, 7, 3, 9, 8};
int n = sizeof(A) / sizeof(A);
int queries[] = {{ 0, 1 },
{ 1, 8 },
{ 0, 2 },
{ 1, 6 },
{ 3, 5 },
{ 7, 9 }
};
int query_count = sizeof(queries) / sizeof(queries);
for (int i = 0; i < query_count; i++) {
int start = queries[i];
int end = queries[i];
cout << "Answer for Query " << (i + 1) << " = " << query(start, end, A) << endl;
}
}

## Output

Answer for Query 1 = 1
Answer for Query 2 = 2
Answer for Query 3 = 1
Answer for Query 4 = 1
Answer for Query 5 = 1
Answer for Query 6 = 0