Static Range Queries allow us to gather information from arrays without updating them.


πŸ”’ 1. Frequency Arrays

🎯 Problem: Count the occurrences of each element in an array.

❌ Naive Approach:

βœ… Efficient Approach:

🧠 Idea: Each index in the frequency array represents the value of the element. The value at that index represents its count.

πŸ§ͺ Example:

A = [8, 5, 4, 6, 5, 8, 5, 4, 2]
Freq = [0, 0, 1, 0, 2, 3, 1, 0, 2]

πŸ“Œ Query Examples:

πŸ’» Code:

const int MAX_VAL = 1e6 + 1;
int main() {
    int n, Freq[MAX_VAL] = {};
    cin >> n;
    vector<int> A(n);
    for (int i = 0; i < n; ++i) {
        cin >> A[i];
        Freq[A[i]]++;
    }
    for (int i = 0; i < n; ++i) {
        if (Freq[A[i]] > 0) {
            cout << "Frequency of " << A[i] << " is " << Freq[A[i]] << ".\\\\n";
            Freq[A[i]] = 0;
        }
    }
}

πŸ“ Notes: