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

In C programming, array range queries for elements with frequency same as value is a problem where we need to find how many elements in a given range appear exactly as many times as their value. For example, if element 3 appears 3 times in the range, it contributes to our answer.

Syntax

int query(int start, int end, int arr[], int n);

Algorithm

The approach uses frequency counting within the specified range −

Begin
    create frequency map for elements in range [start, end]
    count := 0
    for each element-frequency pair (element, freq):
        if element == freq:
            count := count + 1
    return count
End

Example

Let's implement this solution using an array to store frequencies since we're working with C −

#include <stdio.h>
#include <string.h>

#define MAX_VAL 1000

int query(int start, int end, int arr[]) {
    int freq[MAX_VAL] = {0};
    
    // Count frequency of each element in the range
    for (int i = start; i <= end; i++) {
        if (arr[i] < MAX_VAL) {
            freq[arr[i]]++;
        }
    }
    
    int count = 0;
    // Check if frequency equals the element value
    for (int i = 0; i < MAX_VAL; i++) {
        if (freq[i] == i) {
            count++;
        }
    }
    
    return count;
}

int main() {
    int A[] = {1, 5, 2, 3, 1, 3, 5, 7, 3, 9, 8};
    int n = sizeof(A) / sizeof(A[0]);
    
    int queries[][2] = {
        {0, 1}, {1, 8}, {0, 2}, 
        {1, 6}, {3, 5}, {7, 9}
    };
    int query_count = sizeof(queries) / sizeof(queries[0]);
    
    for (int i = 0; i < query_count; i++) {
        int start = queries[i][0];
        int end = queries[i][1];
        printf("Answer for Query %d = %d<br>", i + 1, query(start, end, A));
    }
    
    return 0;
}
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

How It Works

For the array {1, 5, 2, 3, 1, 3, 5, 7, 3, 9, 8} −

  • Query(1, 8): Elements 1 appears 1 time and 3 appears 3 times, so answer is 2
  • Query(0, 2): Element 1 appears 1 time in range [0,2], so answer is 1
  • Query(7, 9): No element has frequency equal to its value, so answer is 0

Time Complexity

The time complexity is O(end - start + MAX_VAL) per query, where MAX_VAL is the maximum possible element value. The space complexity is O(MAX_VAL) for the frequency array.

Conclusion

This approach efficiently solves range queries by counting element frequencies within the specified range and checking if any element's frequency matches its value. The solution works well for arrays with bounded element values.

Updated on: 2026-03-15T11:47:19+05:30

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements