C++ Program for Range Queries for Frequencies of array elements
Last Updated :
06 Jan, 2022
Given an array of n non-negative integers. The task is to find frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type.Â
Examples:Â
Â
Input : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};
left = 2, right = 8, element = 8
left = 2, right = 5, element = 6
Output : 3
1
The element 8 appears 3 times in arr[left-1..right-1]
The element 6 appears 1 time in arr[left-1..right-1]
Naive approach: is to traverse from left to right and update count variable whenever we find the element.Â
Below is the code of Naive approach:-Â
Â
C++
// C++ program to find total count of an element
// in a range
#include<bits/stdc++.h>
using namespace std;
// Returns count of element in arr[left-1..right-1]
int findFrequency(int arr[], int n, int left,
int right, int element)
{
int count = 0;
for (int i=left-1; i<=right; ++i)
if (arr[i] == element)
++count;
return count;
}
// Driver Code
int main()
{
int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};
int n = sizeof(arr) / sizeof(arr[0]);
// Print frequency of 2 from position 1 to 6
cout << "Frequency of 2 from 1 to 6 = "
<< findFrequency(arr, n, 1, 6, 2) << endl;
// Print frequency of 8 from position 4 to 9
cout << "Frequency of 8 from 4 to 9 = "
<< findFrequency(arr, n, 4, 9, 8);
return 0;
}
Output:Â
Frequency of 2 from 1 to 6 = 1
Frequency of 8 from 4 to 9 = 2
Time complexity of this approach is O(right - left + 1) or O(n)Â
Auxiliary space: O(1)
An Efficient approach is to use hashing. In C++, we can use unordered_map
Â
- At first, we will store the position in map[] of every distinct element as a vector like thatÂ
Â
int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};
map[2] = {1, 8}
map[8] = {2, 5, 7}
map[6] = {3, 6}
ans so on...
 - As we can see that elements in map[] are already in sorted order (Because we inserted elements from left to right), the answer boils down to find the total count in that hash map[] using binary search like method.Â
Â
In C++ we can use lower_bound which will returns an iterator pointing to the first element in the range [first, last] which has a value not less than 'left'. and upper_bound returns an iterator pointing to the first element in the range [first,last) which has a value greater than 'right'.Â
 - After that we just need to subtract the upper_bound() and lower_bound() result to get the final answer. For example, suppose if we want to find the total count of 8 in the range from [1 to 6], then the map[8] of lower_bound() function will return the result 0 (pointing to 2) and upper_bound() will return 2 (pointing to 7), so we need to subtract the both the result like 2 - 0 = 2 .Â
Â
Below is the code of above approachÂ
Â
C++
// C++ program to find total count of an element
#include<bits/stdc++.h>
using namespace std;
unordered_map< int, vector<int> > store;
// Returns frequency of element in arr[left-1..right-1]
int findFrequency(int arr[], int n, int left,
int right, int element)
{
// Find the position of first occurrence of element
int a = lower_bound(store[element].begin(),
store[element].end(),
left)
- store[element].begin();
// Find the position of last occurrence of element
int b = upper_bound(store[element].begin(),
store[element].end(),
right)
- store[element].begin();
return b-a;
}
// Driver code
int main()
{
int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};
int n = sizeof(arr) / sizeof(arr[0]);
// Storing the indexes of an element in the map
for (int i=0; i<n; ++i)
store[arr[i]].push_back(i+1); //starting index from 1
// Print frequency of 2 from position 1 to 6
cout << "Frequency of 2 from 1 to 6 = "
<< findFrequency(arr, n, 1, 6, 2) <<endl;
// Print frequency of 8 from position 4 to 9
cout << "Frequency of 8 from 4 to 9 = "
<< findFrequency(arr, n, 4, 9, 8);
return 0;
}
Output:Â
Â
Frequency of 2 from 1 to 6 = 1
Frequency of 8 from 4 to 9 = 2
This approach will be beneficial if we have a large number of queries of an arbitrary range asking the total frequency of particular element.
Time complexity: O(log N) for single query.
Please refer complete article on Range Queries for Frequencies of array elements for more details!
Similar Reads
C++ Program to Find the Frequency of Elements in an Array In C++, arrays are a type of data structure that can store a fixed-size sequential collection of elements of the same type. In this article, we will learn how to find the frequency of elements in an array in C++. Example: Input: Array: {1, 2, 3, 4, 2, 1, 3, 2, 4, 5} Output: Element: 1, Frequency: 2
2 min read
C++ Program for Mean of range in array Given an array of n integers. You are given q queries. Write a program to print the floor value of mean in range l to r for each query in a new line. Examples : Input : arr[] = {1, 2, 3, 4, 5} q = 3 0 2 1 3 0 4 Output : 2 3 3 Here for 0 to 2 (1 + 2 + 3) / 3 = 2 Input : arr[] = {6, 7, 8, 10} q = 2 0
4 min read
Frequency of each element of an array of small ranged values Given an array where elements in small range. The maximum element in the array does not go beyond size of array. Find frequencies of elements. Examples: Input : arr[] = {3, 1, 2, 3, 4, 5, 4} Output: 1-->1 2-->1 3-->2 4-->2 5-->1 Input : arr[] = {1, 2, 2, 1, 2} Output: 1-->2 2-->
6 min read
How to Find Frequency of an Element in a Vector in C++? In C++, vectors are containers that store the elements in contiguous memory locations just like arrays. The frequency of a specific element means how many times that particular element occurs in a vector. In this article, we will learn how to find the frequency of a specific element in a vector in C
2 min read
How to Find the Frequency of an Element in a Set in C++? C++ STL provides a set container that can be used to store unique elements in a sorted order. In this article, we will learn how to find the frequency of an element in a set in C++. Example: Input:set<int>s ={10,20,30,40,50}Output:Frequency of 30 is 1Finding Frequency of an Element in a Set in
2 min read
How to Find Frequency of an Element in a List in C++? In C++, lists are sequence containers that allow non-contiguous memory allocation. They are implemented as doubly-linked lists. The frequency of a specific element means how many times that particular element occurs in a list. In this article, we will learn how to find the frequency of a specific el
2 min read
Find the element having different frequency than other array elements Given an array of N integers. Each element in the array occurs the same number of times except one element. The task is to find this element. Examples: Input : arr[] = {1, 1, 2, 2, 3}Output : 3Input : arr[] = {0, 1, 2, 4, 4}Output : 4The idea is to use a hash table freq to store the frequencies of g
7 min read
How to Find the Frequency of an Element in a Multiset in C++? In C++, a multiset is a container that stores elements in a sorted order and multiple elements can have the same values. In this article, we will learn how to find the frequency of a specific element in a multiset. Example: Input: myMultiset = { 5,2,8,5,8,8} Element: 8 Output: Frequency of 8 is: 3Fi
2 min read
C++ Program to Find the GCDs of given index ranges in an array Write a C++ program for a given array a[0 . . . n-1], the task is to find the GCD from index qs (query start) to qe (query end) where 0 <= qs <= qe <= n-1. Example: Input: arr[] = {2, 3, 60, 90, 50};Index Ranges: {1, 3}, {2, 4}, {0, 2}Output: GCDs of given ranges are 3, 10, 1Explanation: El
5 min read
Count pairs from a given array whose sum lies from a given range Given an array arr[] consisting of N integers and two integers L and R, the task is to count the number of pairs whose sum lies in the range [L, R]. Examples: Input: arr[] = {5, 1, 2}, L = 4, R = 7Output: 2Explanation:The pairs satisfying the necessary conditions are as follows: (5, 1): Sum = 5 + 1
13 min read