Open In App

Count indices with Specific Frequency in Array Range

Last Updated : 03 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array of N elements and num queries, In each query, you are given three numbers L, R, and K and you have to tell, how many indexes are there in between L and R(L <= i <= R) such that the frequency of a[i] from index i to n-1 is K. Follow 0-based indexing

Examples:

Input: N = 5, num = 3, A[] = {1, 1, 3, 4, 3}, Q[][] = {{0, 2, 2}, {0, 2, 1}, {0, 4, 2}}
Output: 2 1 2
Explanation: For query 1: 0 2 2
L = 0, R = 2, K = 2, let, L <= i <= R
For i=0: frequency of a[i] i.e. 1 from i to n-1 is 2.
For i=1: frequency of a[i] i.e. 1 from i to n-1 is 1.
For i=2: frequency of a[i] i.e. 3 from i to n-1 is 2.
Hence we have two elements from index 0 to 2 whose frequency from i to n-1 is 2.
For query 2: 0 2 1
L = 0, R = 2, K = 1
As we can see from the above query that there is only a single element in 0 to 2 whose frequency from i to n-1 is 1.
For query 3: 0 4 2, The answer will be 2 because of the index 0 and 2.

Input: N=5, num=2, A={1,1,1,1,1}, Q={{0,4,2},{0,4,1}}
Output: 1 1
Explanation: For query 1: 0 4 2
L = 0, R = 4, K = 2
let, L <= i <= R, For i = 0: frequency of a[i] i.e. 1 from i to n-1 is 5.
For i=1: frequency of a[i] i.e. 1 from i to n-1 is 4.
For i=2: frequency of a[i] i.e. 1 from i to n-1 is 3.
For i=3: frequency of a[i] i.e. 1 from i to n-1 is 2.
For i=4: frequency of a[i] i.e. 1 from i to n-1 is 1.
Hence we have one elements from index 0 to 4 whose frequency from i to n-1 is 2. Similarly For query 2: there is only 1 element in 0 to 4 whose frequency from i to n-1 is 1.

Approach: To solve the problem follow the below idea:

The intuition is to preprocess all the element’s occurrences in the array. We are trying to find out the occurrences of all the elements between each interval in the array and storing them in another 2-d array. Now since we have the the frequency of each element between each interval so we can easily compute the range L to R.

Step-by-step approach:

  • Create a frequency array (freq) which stores whether the element at i , is present in the array after i or not.
  • The column number denotes the frequency of element represented by ith row from 0 to n.
  • Now traverse the freq array and keep on counting the number of elements that has a particular frequency (denoted by column number)
  • a column now shows all the elements whose frequency is denoted by column number and every ith element represented by row number.
  • this will give us occurrence of ith element from L to R in thee query where traversing the column we can gt to know how many such elements exist.
  • Now traverse the “query” array from 0 to num (length of query array) .
  • Store the values of L , R and K .
  • If L =0 so we have to start from initial then desired value will be temp[R][K] .
  • Else we have to traverse the column K i.e. occurrence column and count the number of elements which have the desired occurrences between L to R.
  • Keep storing values in “ans” array.
  • Return ans.

Below is the implementation of the above approach:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
// Function to solve the queries based on
// given parameters.
vector<int> solveQueries(int N, int num, vector<int>& A,
                         vector<vector<int> >& Q)
{
    vector<int> ans;
 
    // Initializing a 2D vector to store the
    // prefix sum of counts.
    vector<vector<int> > pre(N + 1, vector<int>(N + 1, 0));
 
    // Looping over the array to
    // calculate the counts.
    for (int i = 0; i < N; i++) {
        int cnt = 0;
 
        // Counting the occurrences of the
        // current element.
        for (int j = i; j < N; j++) {
            if (A[i] == A[j]) {
                cnt++;
            }
        }
 
        // Updating the count in the
        // prefix sum vector.
        pre[i][cnt]++;
    }
 
    // Computing the prefix sum for each column
    // in the prefix sum vector.
    for (int i = 0; i < N + 1; i++) {
        for (int j = 1; j < N; j++) {
            pre[j][i] += pre[j - 1][i];
        }
    }
 
    // Looping over the queries to compute
    // the answer for each query.
    for (int i = 0; i < num; i++) {
        int L = Q[i][0];
        int R = Q[i][1];
        int K = Q[i][2];
 
        // Computing the answer based on the
        // prefix sums.
        ans.push_back((L == 0 ? pre[R][K]
                              : pre[R][K] - pre[L - 1][K]));
    }
 
    // Returning the answers for all the queries.
    return ans;
}
 
// Drivers code
int main()
{
    int N = 5;
    int num = 3;
    vector<int> A = { 1, 1, 3, 4, 3 };
    vector<vector<int> > Q
        = { { 0, 2, 2 }, { 0, 2, 1 }, { 0, 4, 2 } };
 
    vector<int> result = solveQueries(N, num, A, Q);
 
    // Printing the results
    for (int i = 0; i < num; i++) {
        cout << "Query " << i + 1 << ": " << result[i]
             << endl;
    }
 
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
 
public class Main {
    // Function to solve the queries based on given
    // parameters.
    static List<Integer>
    solveQueries(int N, int num, List<Integer> A,
                 List<List<Integer> > Q)
    {
        List<Integer> ans = new ArrayList<>();
 
        // Initializing a 2D list to store the prefix sum of
        // counts.
        List<List<Integer> > pre = new ArrayList<>();
        for (int i = 0; i <= N; i++) {
            pre.add(new ArrayList<>());
            for (int j = 0; j <= N; j++) {
                pre.get(i).add(0);
            }
        }
 
        // Looping over the array to calculate the counts.
        for (int i = 0; i < N; i++) {
            int cnt = 0;
 
            // Counting the occurrences of the current
            // element.
            for (int j = i; j < N; j++) {
                if (A.get(i).equals(A.get(j))) {
                    cnt++;
                }
            }
 
            // Updating the count in the prefix sum list.
            pre.get(i).set(cnt, pre.get(i).get(cnt) + 1);
        }
 
        // Computing the prefix sum for each column in the
        // prefix sum list.
        for (int i = 0; i < N + 1; i++) {
            for (int j = 1; j < N; j++) {
                pre.get(j).set(i,
                               pre.get(j).get(i)
                                   + pre.get(j - 1).get(i));
            }
        }
 
        // Looping over the queries to compute the answer
        // for each query.
        for (int i = 0; i < num; i++) {
            int L = Q.get(i).get(0);
            int R = Q.get(i).get(1);
            int K = Q.get(i).get(2);
 
            // Computing the answer based on the prefix
            // sums.
            ans.add((L == 0 ? pre.get(R).get(K)
                            : pre.get(R).get(K)
                                  - pre.get(L - 1).get(K)));
        }
 
        // Returning the answers for all the queries.
        return ans;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int N = 5;
        int num = 3;
        List<Integer> A = List.of(1, 1, 3, 4, 3);
        List<List<Integer> > Q
            = List.of(List.of(0, 2, 2), List.of(0, 2, 1),
                      List.of(0, 4, 2));
 
        List<Integer> result = solveQueries(N, num, A, Q);
 
        // Printing the results
        for (int i = 0; i < num; i++) {
            System.out.println("Query " + (i + 1) + ": "
                               + result.get(i));
        }
    }
}


Python3




def solve_queries(N, num, A, Q):
    ans = []
 
    # Initializing a 2D list to store the prefix sum of counts.
    pre = [[0] * (N + 1) for _ in range(N + 1)]
 
    # Looping over the array to calculate the counts.
    for i in range(N):
        cnt = 0
 
        # Counting the occurrences of the current element.
        for j in range(i, N):
            if A[i] == A[j]:
                cnt += 1
 
        # Updating the count in the prefix sum list.
        pre[i][cnt] += 1
 
    # Computing the prefix sum for each column in the prefix sum list.
    for i in range(N + 1):
        for j in range(1, N):
            pre[j][i] += pre[j - 1][i]
 
    # Looping over the queries to compute the answer for each query.
    for i in range(num):
        L, R, K = Q[i]
 
        # Computing the answer based on the prefix sums.
        ans.append(pre[R][K] if L == 0 else pre[R][K] - pre[L - 1][K])
 
    # Returning the answers for all the queries.
    return ans
 
# Drivers code
 
 
def main():
    N = 5
    num = 3
    A = [1, 1, 3, 4, 3]
    Q = [[0, 2, 2], [0, 2, 1], [0, 4, 2]]
 
    result = solve_queries(N, num, A, Q)
 
    # Printing the results
    for i in range(num):
        print(f"Query {i + 1}: {result[i]}")
 
 
if __name__ == "__main__":
    main()


C#




using System;
using System.Collections.Generic;
 
class Program
{
    // Function to solve the queries based on
    // given parameters.
    static List<int> SolveQueries(int N, int num, List<int> A, List<List<int>> Q)
    {
        List<int> ans = new List<int>();
 
        // Initializing a 2D list to store the
        // prefix sum of counts.
        List<List<int>> pre = new List<List<int>>(N + 1);
        for (int i = 0; i <= N; i++)
        {
            pre.Add(new List<int>(new int[N + 1]));
        }
 
        // Looping over the array to
        // calculate the counts.
        for (int i = 0; i < N; i++)
        {
            int cnt = 0;
 
            // Counting the occurrences of the
            // current element.
            for (int j = i; j < N; j++)
            {
                if (A[i] == A[j])
                {
                    cnt++;
                }
            }
 
            // Updating the count in the
            // prefix sum list.
            pre[i][cnt]++;
        }
 
        // Computing the prefix sum for each column
        // in the prefix sum list.
        for (int i = 0; i < N + 1; i++)
        {
            for (int j = 1; j < N; j++)
            {
                pre[j][i] += pre[j - 1][i];
            }
        }
 
        // Looping over the queries to compute
        // the answer for each query.
        for (int i = 0; i < num; i++)
        {
            int L = Q[i][0];
            int R = Q[i][1];
            int K = Q[i][2];
 
            // Computing the answer based on the
            // prefix sums.
            ans.Add((L == 0 ? pre[R][K] : pre[R][K] - pre[L - 1][K]));
        }
 
        // Returning the answers for all the queries.
        return ans;
    }
 
    // Drivers code
    static void Main()
    {
        int N = 5;
        int num = 3;
        List<int> A = new List<int> { 1, 1, 3, 4, 3 };
        List<List<int>> Q = new List<List<int>> { new List<int> { 0, 2, 2 }, new List<int> { 0, 2, 1 }, new List<int> { 0, 4, 2 } };
 
        List<int> result = SolveQueries(N, num, A, Q);
 
        // Printing the results
        for (int i = 0; i < num; i++)
        {
            Console.WriteLine($"Query {i + 1}: {result[i]}");
        }
    }
}
 
// This code is contributed by rambabuguphka


Javascript




function solveQueries(N, num, A, Q) {
    const ans = [];
 
    // Initializing a 2D array to store the prefix sum of counts.
    const pre = Array.from({ length: N + 1 }, () => Array(N + 1).fill(0));
 
    // Looping over the array to calculate the counts.
    for (let i = 0; i < N; i++) {
        let cnt = 0;
 
        // Counting the occurrences of the current element.
        for (let j = i; j < N; j++) {
            if (A[i] === A[j]) {
                cnt += 1;
            }
        }
 
        // Updating the count in the prefix sum array.
        pre[i][cnt] += 1;
    }
 
    // Computing the prefix sum for each column in the prefix sum array.
    for (let i = 0; i <= N; i++) {
        for (let j = 1; j < N; j++) {
            pre[j][i] += pre[j - 1][i];
        }
    }
 
    // Looping over the queries to compute the answer for each query.
    for (let i = 0; i < num; i++) {
        const [L, R, K] = Q[i];
 
        // Computing the answer based on the prefix sums.
        ans.push(L === 0 ? pre[R][K] : pre[R][K] - pre[L - 1][K]);
    }
 
    // Returning the answers for all the queries.
    return ans;
}
 
// Driver code
const N = 5;
const num = 3;
const A = [1, 1, 3, 4, 3];
const Q = [[0, 2, 2], [0, 2, 1], [0, 4, 2]];
 
const result = solveQueries(N, num, A, Q);
 
// Printing the results
for (let i = 0; i < num; i++) {
  console.log(`Query ${i + 1}: ${result[i]}`);
}


Output

Query 1: 2
Query 2: 1
Query 3: 2










Time Complexity: O(N2)
Auxiliary Space: O(N2)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads