Queries for elements having values within the range A to B using MO's Algorithm
Last Updated :
10 Nov, 2023
Prerequisites: MO's algorithm, SQRT Decomposition
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[] = {3, 4, 6, 2, 7, 1}, A = 1, B = 6, query = {0, 4}
Output: 4
Explanation:
All 3, 4, 6, 2 lies within 1 to 6 in the subarray {3, 4, 6, 2}
Therefore, the count of such elements is 4.
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.
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:
- Group the queries into multiple chunks where each chunk contains the values of starting range in (0 to ?N - 1), (?N to 2x?N - 1), and so on. Sort the queries within a chunk in increasing order of R.
- Process all queries one by one in a way that every query uses result computed in the previous query.
- Maintain the frequency array that will count the frequency of arr[i] as they appear in the range [L, R].
For example:
arr[] = [3, 4, 6, 2, 7, 1], L = 0, R = 4 and A = 1, B = 6
Initially frequency array is initialized to 0 i.e freq[]=[0….0]
Step 1: Add arr[0] and increment its frequency as freq[arr[0]]++
i.e freq[3]++ and freq[]=[0, 0, 0, 1, 0, 0, 0, 0]
Step 2: Add arr[1] and increment freq[arr[1]]++
i.e freq[4]++ and freq[]=[0, 0, 0, 1, 1, 0, 0, 0]
Step 3: Add arr[2] and increment freq[arr[2]]++
i.e freq[6]++ and freq[]=[0, 0, 0, 1, 1, 0, 1, 0]
Step 4: Add arr[3] and increment freq[arr[3]]++
i.e freq[2]++ and freq[]=[0, 0, 1, 1, 1, 0, 1, 0]
Step 5: Add arr[4] and increment freq[arr[4]]++
i.e freq[7]++ and freq[]=[0, 0, 1, 1, 1, 0, 1, 1]
Step 6: Now we need to find the numbers of elements between A and B.
Step 7: The answer is equal to \sum_{i=A}^B freq[i]
To calculate the sum in Step 7, we cannot do iteration because that would lead to O(N) time complexity per query. So we will use square root decomposition technique to find the sum, whose time complexity is O(?N) per query.
Below is the implementation of the above approach:
C++
// C++ implementation to find the
// values in the range A to B
// in a subarray of L to R
#include <bits/stdc++.h>
using namespace std;
#define MAX 100001
#define SQRSIZE 400
// Variable to represent block size.
// This is made global so compare()
// of sort can use it.
int query_blk_sz;
// Structure to represent a query range
struct Query {
int L;
int R;
};
// Frequency array
// to keep count of elements
int frequency[MAX];
// Array which contains the frequency
// of a particular block
int blocks[SQRSIZE];
// Block size
int blk_sz;
// Function used to sort all queries
// so that all queries of the same
// block are arranged together and
// within a block, queries are sorted
// in increasing order of R values.
bool compare(Query x, Query y)
{
if (x.L / query_blk_sz
!= y.L / query_blk_sz)
return (x.L / query_blk_sz
< y.L / query_blk_sz);
return x.R < y.R;
}
// Function used to get the block
// number of current a[i] i.e ind
int getblocknumber(int ind)
{
return (ind) / blk_sz;
}
// Function to get the answer
// of range [0, k] which uses the
// sqrt decomposition technique
int getans(int A, int B)
{
int ans = 0;
int left_blk, right_blk;
left_blk = getblocknumber(A);
right_blk = getblocknumber(B);
// If left block is equal to right block
// then we can traverse that block
if (left_blk == right_blk) {
for (int i = A; i <= B; i++)
ans += frequency[i];
}
else {
// Traversing first block in
// range
for (int i = A;
i < (left_blk + 1) * blk_sz;
i++)
ans += frequency[i];
// Traversing completely overlapped
// blocks in range
for (int i = left_blk + 1;
i < right_blk; i++)
ans += blocks[i];
// Traversing last block in range
for (int i = right_blk * blk_sz;
i <= B; i++)
ans += frequency[i];
}
return ans;
}
void add(int ind, int a[])
{
// Increment the frequency of a[ind]
// in the frequency array
frequency[a[ind]]++;
// Get the block number of a[ind]
// to update the result in blocks
int block_num = getblocknumber(a[ind]);
blocks[block_num]++;
}
void remove(int ind, int a[])
{
// Decrement the frequency of
// a[ind] in the frequency array
frequency[a[ind]]--;
// Get the block number of a[ind]
// to update the result in blocks
int block_num = getblocknumber(a[ind]);
blocks[block_num]--;
}
void queryResults(int a[], int n,
Query q[], int m,
int A, int B)
{
// Initialize the block size
// for queries
query_blk_sz = sqrt(m);
// Sort all queries so that queries
// of same blocks are arranged
// together.
sort(q, q + m, compare);
// Initialize current L,
// current R and current result
int currL = 0, currR = 0;
for (int i = 0; i < m; i++) {
// L and R values of the
// current range
int L = q[i].L, R = q[i].R;
// Add Elements of current
// range
while (currR <= R) {
add(currR, a);
currR++;
}
while (currL > L) {
add(currL - 1, a);
currL--;
}
// Remove element of previous
// range
while (currR > R + 1)
{
remove(currR - 1, a);
currR--;
}
while (currL < L) {
remove(currL, a);
currL++;
}
printf("%d\n", getans(A, B));
}
}
// Driver code
int main()
{
int arr[] = { 3, 4, 6, 2, 7, 1 };
int N = sizeof(arr) / sizeof(arr[0]);
int A = 1, B = 6;
blk_sz = sqrt(N);
Query Q[] = { { 0, 4 } };
int M = sizeof(Q) / sizeof(Q[0]);
// Answer the queries
queryResults(arr, N, Q, M, A, B);
return 0;
}
Java
// Java implementation to find the
// values in the range A to B
// in a subarray of L to R
import java.util.Arrays;
public class GFG {
static final int MAX = 100001;
static final int SQRSIZE = 400;
// Variable to represent block size.
// This is made global so compare()
// of sort can use it.
static int query_blk_sz;
// Structure to represent a query range
static class Query {
int L;
int R;
public Query(int l, int r)
{
L = l;
R = r;
}
}
// Frequency array
// to keep count of elements
static int[] frequency = new int[MAX];
// Array which contains the frequency
// of a particular block
static int[] blocks = new int[SQRSIZE];
// Block size
static int blk_sz;
// Function used to sort all queries
// so that all queries of the same
// block are arranged together and
// within a block, queries are sorted
// in increasing order of R values.
static boolean compare(Query x, Query y)
{
if (x.L / query_blk_sz != y.L / query_blk_sz)
return (x.L / query_blk_sz
< y.L / query_blk_sz);
return x.R < y.R;
}
// Function used to get the block
// number of current a[i] i.e ind
static int getblocknumber(int ind)
{
return (ind) / blk_sz;
}
// Function to get the answer
// of range [0, k] which uses the
// sqrt decomposition technique
static int getans(int A, int B)
{
int ans = 0;
int left_blk, right_blk;
left_blk = getblocknumber(A);
right_blk = getblocknumber(B);
// If left block is equal to right block
// then we can traverse that block
if (left_blk == right_blk) {
for (int i = A; i <= B; i++)
ans += frequency[i];
}
else {
// Traversing first block in
// range
for (int i = A; i < (left_blk + 1) * blk_sz;
i++)
ans += frequency[i];
// Traversing completely overlapped
// blocks in range
for (int i = left_blk + 1; i < right_blk; i++)
ans += blocks[i];
// Traversing last block in range
for (int i = right_blk * blk_sz; i <= B; i++)
ans += frequency[i];
}
return ans;
}
static void add(int ind, int a[])
{
// Increment the frequency of a[ind]
// in the frequency array
frequency[a[ind]]++;
// Get the block number of a[ind]
// to update the result in blocks
int block_num = getblocknumber(a[ind]);
blocks[block_num]++;
}
static void remove(int ind, int a[])
{
// Decrement the frequency of
// a[ind] in the frequency array
frequency[a[ind]]--;
// Get the block number of a[ind]
// to update the result in blocks
int block_num = getblocknumber(a[ind]);
blocks[block_num]--;
}
static void queryResults(int a[], int n, Query q[],
int m, int A, int B)
{
// Initialize the block size
// for queries
query_blk_sz = (int)Math.sqrt(m);
// Sort all queries so that queries
// of same blocks are arranged
// together.
Arrays.parallelSort(q, (x, y) -> {
if (x.L / query_blk_sz != y.L / query_blk_sz)
return (x.L / query_blk_sz
- y.L / query_blk_sz);
return x.R - y.R;
});
// Initialize current L,
// current R and current result
int currL = 0, currR = 0;
for (int i = 0; i < m; i++) {
// L and R values of the
// current range
int L = q[i].L, R = q[i].R;
// Add Elements of current
// range
while (currR <= R) {
add(currR, a);
currR++;
}
while (currL > L) {
add(currL - 1, a);
currL--;
}
// Remove element of previous
// range
while (currR > R + 1)
{
remove(currR - 1, a);
currR--;
}
while (currL < L) {
remove(currL, a);
currL++;
}
System.out.println(getans(A, B));
}
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 3, 4, 6, 2, 7, 1 };
int N = arr.length;
int A = 1, B = 6;
blk_sz = (int)Math.sqrt(N);
Query Q[] = { new Query(0, 4) };
int M = Q.length;
// Answer the queries
queryResults(arr, N, Q, M, A, B);
}
}
// This code is contributed by Lovely Jain
Python3
# Python implementation to find the
# values in the range A to B
# in a subarray of L to R
import math
MAX = 100001
SQRSIZE = 400
# Structure to represent a query range
class Query:
def __init__(self, l, r):
self.L = l
self.R = r
# Frequency array
# to keep count of elements
frequency = [0] * MAX
blocks = [0] * SQRSIZE
# Function used to sort all queries
# so that all queries of the same
# block are arranged together and
# within a block, queries are sorted
# in increasing order of R values.
def compare(x, y):
if x.L // query_blk_sz != y.L // query_blk_sz:
return x.L // query_blk_sz < y.L // query_blk_sz
return x.R < y.R
# Function used to get the block
# number of current a[i] i.e ind
def getblocknumber(ind):
return ind // blk_sz
# Function to get the answer
# of range [0, k] which uses the
# sqrt decomposition technique
def getans(A, B):
ans = 0
left_blk = getblocknumber(A)
right_blk = getblocknumber(B)
# If left block is equal to right block
# then we can traverse that block
if left_blk == right_blk:
for i in range(A, B+1):
ans += frequency[i]
else:
for i in range(A, (left_blk+1)*blk_sz):
ans += frequency[i]
# Traversing completely overlapped
# blocks in range
for i in range(left_blk+1, right_blk):
ans += blocks[i]
# Traversing last block in range
for i in range(right_blk*blk_sz, B+1):
ans += frequency[i]
return ans
def add(ind, a):
# Increment the frequency of a[ind]
# in the frequency array
frequency[a[ind]] += 1
# Get the block number of a[ind]
# to update the result in blocks
block_num = getblocknumber(a[ind])
blocks[block_num] += 1
def remove(ind, a):
# Decrement the frequency of
# a[ind] in the frequency array
frequency[a[ind]] -= 1
# Get the block number of a[ind]
# to update the result in blocks
block_num = getblocknumber(a[ind])
blocks[block_num] -= 1
def queryResults(a, n, q, m, A, B):
# Initialize the block size
# for queries
global blk_sz, query_blk_sz
query_blk_sz = int(math.sqrt(m))
# Sort all queries so that queries
# of same blocks are arranged
# together
q.sort(key=lambda x: (x.L // query_blk_sz, x.R))
# Initialize current L,
# current R and current result
currL, currR = 0, 0
for i in range(m):
# L and R values of the
# current range
L, R = q[i].L, q[i].R
# Add Elements of current
# range
while currR <= R:
add(currR, a)
currR += 1
while currL > L:
add(currL - 1, a)
currL -= 1
# Remove element of previous
# range
while currR > R + 1:
remove(currR - 1, a)
currR -= 1
while currL < L:
remove(currL, a)
currL += 1
print(getans(A, B))
# Driver code
if __name__ == '__main__':
arr = [3, 4, 6, 2, 7, 1]
N = len(arr)
A, B = 1, 6
blk_sz = int(math.sqrt(N))
Q = [Query(0, 4)]
M = len(Q)
queryResults(arr, N, Q, M, A, B)
# This code is contributed by Shivhack999
C#
using System;
class GFG
{
static readonly int MAX = 100001;
static readonly int SQRSIZE = 400;
// Variable to represent block size.
// This is made global so compare()
// of sort can use it.
static int query_blk_sz;
// Structure to represent a query range
class Query
{
public int L;
public int R;
public Query(int l, int r)
{
L = l;
R = r;
}
}
// Frequency array
// to keep count of elements
static int[] frequency = new int[MAX];
// Array which contains the frequency
// of a particular block
static int[] blocks = new int[SQRSIZE];
// Block size
static int blk_sz;
// Function used to sort all queries
// so that all queries of the same
// block are arranged together and
// within a block, queries are sorted
// in increasing order of R values.
static bool compare(Query x, Query y)
{
if (x.L / query_blk_sz != y.L / query_blk_sz)
return (x.L / query_blk_sz < y.L / query_blk_sz);
return x.R < y.R;
}
// Function used to get the block
// number of current a[i] i.e ind
static int getblocknumber(int ind)
{
return (ind) / blk_sz;
}
// Function to get the answer
// of range [0, k] which uses the
// sqrt decomposition technique
static int getans(int A, int B)
{
int ans = 0;
int left_blk, right_blk;
left_blk = getblocknumber(A);
right_blk = getblocknumber(B);
// If left block is equal to right block
// then we can traverse that block
if (left_blk == right_blk)
{
for (int i = A; i <= B; i++)
ans += frequency[i];
}
else
{
// Traversing first block in
// range
for (int i = A; i < (left_blk + 1) * blk_sz; i++)
ans += frequency[i];
// Traversing completely overlapped
// blocks in range
for (int i = left_blk + 1; i < right_blk; i++)
ans += blocks[i];
// Traversing last block in range
for (int i = right_blk * blk_sz; i <= B; i++)
ans += frequency[i];
}
return ans;
}
static void add(int ind, int[] a)
{
// Increment the frequency of a[ind]
// in the frequency array
frequency[a[ind]]++;
// Get the block number of a[ind]
// to update the result in blocks
int block_num = getblocknumber(a[ind]);
blocks[block_num]++;
}
static void remove(int ind, int[] a)
{
// Decrement the frequency of
// a[ind] in the frequency array
frequency[a[ind]]--;
// Get the block number of a[ind]
// to update the result in blocks
int block_num = getblocknumber(a[ind]);
blocks[block_num]--;
}
static void queryResults(int[] a, int n, Query[] q, int m, int A, int B)
{
// Initialize the block size
// for queries
query_blk_sz = (int)Math.Sqrt(m);
// Sort all queries so that queries
// of same blocks are arranged
// together.
Array.Sort(q, (x, y) =>
{
if (x.L / query_blk_sz != y.L / query_blk_sz)
return (x.L / query_blk_sz - y.L / query_blk_sz);
return x.R - y.R;
});
// Initialize current L,
// current R and current result
int currL = 0, currR = 0;
for (int i = 0; i < m; i++)
{
// L and R values of the
// current range
int L = q[i].L, R = q[i].R;
// Add Elements of current
// range
while (currR <= R)
{
add(currR, a);
currR++;
}
while (currL > L)
{
add(currL - 1, a);
currL--;
}
// Remove element of previous
// range
while (currR > R + 1)
{
remove(currR - 1, a);
currR--;
}
while (currL < L)
{
remove(currL, a);
currL++;
}
Console.WriteLine(getans(A, B));
}
}
// Driver code
public static void Main()
{
int[] arr = { 3, 4, 6, 2, 7, 1 };
int N = arr.Length;
int A = 1, B = 6;
blk_sz = (int)Math.Sqrt(N);
Query[] Q = { new Query(0, 4) };
int M = Q.Length;
// Answer the queries
queryResults(arr, N, Q, M, A, B);
}
}
JavaScript
// Declare constants
const MAX = 100001;
const SQRSIZE = 400;
// Declare empty arrays
let frequency = new Array(MAX).fill(0);
let blocks = new Array(SQRSIZE).fill(0);
// Define Query class
class Query {
constructor(l, r) {
this.L = l;
this.R = r;
}
}
// Function to compare two Query objects
function compare(x, y) {
// Compare the left values of the queries
if (Math.floor(x.L / query_blk_sz) !== Math.floor(y.L / query_blk_sz)) {
return Math.floor(x.L / query_blk_sz) < Math.floor(y.L / query_blk_sz);
}
// Compare the right values of the queries
return x.R < y.R;
}
// Function to get the block number of a given index
function getblocknumber(ind) {
return Math.floor(ind / blk_sz);
}
// Function to get the answer
function getans(A, B) {
let ans = 0;
let left_blk = getblocknumber(A);
let right_blk = getblocknumber(B);
// If the left and right blocks are the same,
// add the frequencies between A and B
if (left_blk === right_blk) {
for (let i = A; i <= B; i++) {
ans += frequency[i];
}
// If the left and right blocks are different,
// add the frequencies between A and the end of the left block,
// add all the frequencies of blocks between the left and right block,
// and add the frequencies between the start of the right block and B
} else {
for (let i = A; i <= (left_blk + 1) * blk_sz - 1; i++) {
ans += frequency[i];
}
for (let i = left_blk + 1; i < right_blk; i++) {
ans += blocks[i];
}
for (let i = right_blk * blk_sz; i <= B; i++) {
ans += frequency[i];
}
}
return ans;
}
// Function to add the frequency of a given index
function add(ind, a) {
frequency[a[ind]]++;
let block_num = getblocknumber(a[ind]);
blocks[block_num]++;
}
// Function to remove the frequency of a given index
function remove(ind, a) {
frequency[a[ind]]--;
let block_num = getblocknumber(a[ind]);
blocks[block_num]--;
}
// Function to get the query results
function queryResults(a, n, q, m, A, B) {
// Define block sizes
let blk_sz, query_blk_sz;
query_blk_sz = Math.floor(Math.sqrt(m));
// Sort the queries
q.sort(compare);
// Initialize left and right indices
let currL = 0,
currR = 0;
// Iterate through queries
for (let i = 0; i < m; i++) {
// Get the left and right indices of the query
let L = q[i].L,
R = q[i].R;
// Add the frequency of all indices between the current
// right index and the right index of the query
while (currR <= R) {
add(currR, a);
currR++;
}
// Add the frequency of all indices between the current left index
// and the left index of the query
while (currL > L) {
add(currL - 1, a);
currL--;
}
// Remove the frequency of all indices between the current
// right index and the right index of the query
while (currR > R + 1) {
remove(currR - 1, a);
currR--;
}
// Remove the frequency of all indices between the current left
// index and the left index of the query
while (currL < L) {
remove(currL, a);
currL++;
}
// Log the answer
console.log(getans(A, B));
}
}
// Declare an array, the left and right indices, and an array of queries
let arr = [3, 4, 6, 2, 7, 1];
let N = arr.length;
let A = 1,
B = 6;
let blk_sz = Math.floor(Math.sqrt(N));
let Q = [new Query(0, 4)];
let M = Q.length;
// Log the query results
queryResults(arr, N, Q, M, A, B);
Time Complexity: O(Q*?N)
Space Complexity: O(N), since N extra space has been taken.
Similar Reads
Print all Repetitive elements in given Array within value range [A, B] for Q queries
Given an array arr[] of size N, and Q queries of the form [A, B], the task is to find all the unique elements from the array which are repetitive and their values lie between A and B (both inclusive) for each of the Q queries. Examples: Input: arr[] = { 1, 5, 1, 2, 3, 3, 4, 0, 0 }, Q = 2, queries={
13 min read
Queries for count of array elements with values in given range with updates
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,
15+ min read
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 =
15+ min read
Queries to find the minimum index in a range [L, R] having at least value X with updates
Given an array arr[] consisting of N integers and an array Queries[] consisting of Q queries of the type {X, L, R} to perform following operations: If the value of X is 1, then update the array element at Xth index to L.Otherwise, find the minimum index j in the range [L, R] such that arr[j] ? X. If
15+ min read
Array range queries for searching an element
Given an array of N elements and Q queries of the form L R X. For each query, you have to output if the element X exists in the array between the indices L and R(included). Prerequisite : Mo's Algorithms Examples : Input : N = 5 arr = [1, 1, 5, 4, 5] Q = 3 1 3 2 2 5 1 3 5 5 Output : No Yes Yes Expla
15+ min read
Queries for counts of array values in a given range
Given an unsorted array of integers and a set of m queries, where each query consists of two integers x and y, the task is to determine the number of elements in the array that lie within the range [x, y] (inclusive) for each query.Examples: Input: arr = [1, 3, 4, 9, 10, 3], queries = [[1, 4], [9, 1
15+ min read
Queries to increment array elements in a given range by a given value for a given number of times
Given an array, arr[] of N positive integers and M queries of the form {a, b, val, f}. The task is to print the array after performing each query to increment array elements in the range [a, b] by a value val f number of times. Examples: Input: arr[] = {1, 2, 3}, M=3, Q[][] = {{1, 2, 1, 4}, {1, 3, 2
13 min read
Range Queries for count of Armstrong numbers in subarray using MO's algorithm
Given an array arr[] consisting of N elements and Q queries represented by L and R denoting a range, the task is to print the number of Armstrong numbers in the subarray [L, R]. Examples: Input: arr[] = {18, 153, 8, 9, 14, 5} Query 1: query(L=0, R=5) Query 2: query(L=3, R=5) Output: 4 2 Explanation:
15 min read
Queries to count array elements greater than or equal to a given number with updates
Given two arrays arr[] and query[] of sizes N and Q respectively and an integer M, the task for each query, is to count the number of array elements that are greater than or equal to query[i] and decrease all such numbers by M and perform the rest of the queries on the updated array. Examples: Input
15+ min read
Find the minimum range size that contains the given element for Q queries
Given an array Intervals[] consisting of N pairs of integers where each pair is denoting the value range [L, R]. Also, given an integer array Q[] consisting of M queries. For each query, the task is to find the size of the smallest range that contains that element. Return -1 if no valid interval exi
12 min read