Range Queries to count elements lying in a given Range : MO’s Algorithm

Given an array arr[] of N elements and two integers A to B, the task is to answer Q queries each having two integers L and R. For each query, find the number of elements in the subarray arr[L…R] which lies within the range A to B (inclusive).

Examples:

Input: arr[] = {7, 3, 9, 13, 5, 4}, A = 4, B = 7
query = {1, 5}
Output: 2
Explanation:
Only 5 and 4 lies within 4 to 7
in the subarray {3, 9, 13, 5, 4}
Therefore, the count of such elements is 2.

Input: arr[] = {0, 1, 2, 3, 4, 5, 6, 7}, A = 1, B = 5
query = {3, 5}
Output: 3
Explanation:
All the elements 3, 4 and 5 lies within
the range 1 to 5 in the subarray {3, 4, 5}.
Therefore, the count of such elements is 3.

Prerequisites: MO’s algorithm, SQRT Decomposition



Approach: The idea is to use MO’s algorithm to pre-process all queries so that result of one query can be used in the next query. Below is the illustration of the steps:

Article Tags :
Practice Tags :