Count indices with Specific Frequency in Array Range
Last Updated :
03 Jan, 2024
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]}`);
}
OutputQuery 1: 2
Query 2: 1
Query 3: 2
Time Complexity: O(N2)
Auxiliary Space: O(N2)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms
DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Breadth First Search or BFS for a Graph
Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Data Structures Tutorial
Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all
Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read