VOOZH about

URL: https://www.geeksforgeeks.org/dsa/queries-for-count-of-array-elements-with-values-in-given-range-with-updates/

⇱ Queries for count of array elements with values in given range with updates - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Queries for count of array elements with values in given range with updates

Last Updated : 15 Jul, 2025

Given an array arr[] of size N and a matrix Q consisting of queries of the following two types: 

  • 1 L R : Print the number of elements lying in the range [L, R].
  • 2 i x : Set arr[i] = x

Examples: 

Input: arr[] = {1, 2, 2, 3, 4, 4, 5, 6}, Q = {{1, {3, 5}}, {1, {2, 4}}, {1, {1, 2}}, {2, {1, 7}}, {1, {1, 2}}} 
Output: 4 5 3 2 
Explanation: 
Array elements from the range [3, 5] are {3, 4, 4, 5} 
Array elements from the range [2, 4] are {2, 2, 3, 4, 4} 
Array elements from the range [1, 2] are {1, 2, 2} 
Replacing arr[1] by 7 modifies the array to {1, 7, 2, 3, 4, 4, 5, 6} 
Elements that lie in range [1, 2] are {1, 2}

Input: arr = {5, 5, 1, 3, 4, 4, 2, 3}, Q = {{1, {3, 6}}, {1, {2, 4}}, {1, {10, 20}}} 
Output: 6 5 0 
Explanation: 
Array elements from the range [3, 6] are {3, 3, 4, 4, 5, 5} 
Array elements from the range [2, 4] are {2, 3, 3, 4, 4} 
No element from the range [10, 20] exists in the array. 

Naive Approach: 
The simplest approach to solve this problem is as follows: 

  • For the query of type (1 L R), iterate over the entire array and count the number of elements in the array such that L ? arr[i] ? R. Finally, print the count.
  • For the query of type (2 i x), replace arr[i] by x.

Below is the implementation of the above approach:


Output: 
4 5 3 2

 

Time Complexity: O(Q * N) 
Auxiliary Space: O(1)

Efficient Approach: 
The above approach can be optimized using Fenwick Tree. Follow the steps below to solve the problem: 

  • Construct a Fenwick tree from the given array.
  • Fenwick tree will be represented as an array of size equal to maximum element in the array, so that the array elements can be used as index (idea is similar to this approach).
  • Traverse the array and increase the frequency of every element by calling the update method of Fenwick tree.
  • For each query of type (1 L R), call the getSum method of Fenwick tree. The answer for the query of type 1 will be:

getSum(R) – getSum(L - 1)

  • For each query of type (2 i x), call the update method of Fenwick tree to increase the frequency of the added element and decrease the count of the element to be replaced. 
     

Below is the implementation of the above approach:


Output: 
4 5 3 2

 

Time Complexity: O(n*log(N) + Q*log(N)) 
Auxiliary Space: O(maxm), where maxm is the maximum element present in the array.
 

Comment