VOOZH about

URL: https://www.geeksforgeeks.org/dsa/number-elements-less-equal-given-number-given-subarray-set-2-including-updates/

⇱ Number of elements less than or equal to a given number in a given subarray | Set 2 (Including Updates) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of elements less than or equal to a given number in a given subarray | Set 2 (Including Updates)

Last Updated : 23 Jul, 2025

Given an array 'a[]' and number of queries q there will be two type of queries

  1. Query 0 update(i, v) : Two integers i and v which means set a[i] = v
  2. Query 1 count(l, r, k): We need to print number of integers less than equal to k in the subarray l to r.

Given a[i], v <= 10000 Examples :

Input : arr[] = {5, 1, 2, 3, 4}
 q = 6
 1 1 3 1 // First value 1 means type of query is count()
 0 3 10 // First value 0 means type of query is update()
 1 3 3 4
 0 2 1
 0 0 2
 1 0 4 5
Output :
1
0
4
For first query number of values less than equal to 1 in 
arr[1..3] is 1(1 only), update a[3] = 10
There is no value less than equal to 4 in the a[3..3]
and similarly other queries are answered 

We have discussed a solution that handles only count() queries in below post.Number of elements less than or equal to a given number in a given subarray Here update() query also needs to be handled. Naive Approach The naive approach is whenever there is update operation update the array and whenever type 2 query is there traverse the subarray and count the valid elements. Efficient Approach The idea is to use square root decomposition 

  1. Step 1 : Divide the array in sqrt(n) equal sized blocks. For each block keep a binary index tree of size equal to 1 more than the maximum possible element in the array of the elements in that block.
  2. Step 2: For each element of the array find out the block to which it belongs and update the bit array of that block with the value 1 at arr[i].
  3. Step 3: Whenever there is a update query, update the bit array of the corresponding block at the original value of the array at that index with value equal to -1 and update the bit array of the same block with value 1 at the new value of the array at that index.
  4. Step 4: For type 2 query you can make a single query to the BIT (to count elements less than or equal to k) for each complete block in the range, and for the two partial blocks on the end, just loop through the elements.

Output:

1
0
4

Time Complexity: O(n log(max_element))

Space Complexity: O(sqrt(n) log(max_element))

The question is know why not to use this method when there were no update operations the answer lies in space complexity in this method 2-d bit array is used as well as its size depends upon the maximum possible value of the array but when there was no update operation our bit array was only dependent on the size of array.

Comment