Number of elements less than or equal to a number in a subarray : MO's Algorithm
Last Updated :
12 Jul, 2025
Given an array arr of size N and Q queries of the form L, R and X, the task is to print the number of elements less than or equal to X in the subarray represented by L to R.
Prerequisites: MO's Algorithm, Sqrt Decomposition
Examples:
Input:
arr[] = {2, 3, 4, 5}
Q = {{0, 3, 5}, {0, 2, 2}}
Output:
4
1
Explanation:
Number of elements less than or equal to 5
in arr[0..3] is 4 (all elements)
Number of elements less than or equal to 2
in arr[0..2] is 1 (only 2)
Approach:
The idea of MO’s algorithm is to pre-process all queries so that result of one query can be used in the next query.
Let arr[0…n-1] be input array and Q[0..m-1] be an array of queries.
- Sort all queries in a way that queries with L values from 0 to ?n – 1 are put together, then all queries from ?n to 2×?n – 1, and so on. All queries within a block are sorted in increasing order of R values.
- Process all queries one by one in a way that every query uses result computed in the previous query.
- We will 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 X=5
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 less than or equal to X(here X=5).
Step 7- The answer is equal to \sum_{i=0}^{X} 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 sqrt decomposition technique to find the sum whose time complexity is O(?n) per query.
C++
// C++ program to answer queries to
// count number of elements smaller
// than or equal to x.
#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;
int x;
};
// 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 k)
{
int ans = 0;
int left_blk, right_blk;
left_blk = 0;
right_blk = getblocknumber(k);
// If left block is equal to
// right block then we can traverse
// that block
if (left_blk == right_blk) {
for (int i = 0; i <= k; i++)
ans += frequency[i];
}
else {
// Traversing first block in
// range
for (int i = 0; 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 <= k; 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)
{
// 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,
x = q[i].x;
// 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("query[%d, %d, %d] : %d\n",
L, R, x, getans(x));
}
}
// Driver code
int main()
{
int arr[] = { 2, 0, 3, 1, 4, 2, 5, 11 };
int N = sizeof(arr) / sizeof(arr[0]);
blk_sz = sqrt(N);
Query Q[] = { { 0, 2, 2 }, { 0, 3, 5 },
{ 5, 7, 10 } };
int M = sizeof(Q) / sizeof(Q[0]);
// Answer the queries
queryResults(arr, N, Q, M);
return 0;
}
Java
import java.util.*;
public class GFG{
static int MAX = 100001;
static int SQRSIZE = 400;
// Variable to represent block size.
// This is made global so compare()
// of sort can use it.
static int query_blk_sz;
// 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];
static int blk_sz;
// class to represent a
// query range
static class Query {
int L;
int R;
int x;
Query(int a,int b,int c)
{
L = a;
R = b;
x = c;
}
}
// 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 k) {
int ans = 0;
int left_blk, right_blk;
left_blk = 0;
right_blk = getblocknumber(k);
// If left block is equal to
// right block then we can traverse
// that block
if (left_blk == right_blk) {
for (int i = 0; i <= k; i++) {
ans += frequency[i];
}
} else {
// Traversing first block in
// range
for (int i = 0; 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 <= k; 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) {
query_blk_sz = (int) Math.sqrt(m);
Arrays.sort(q, new Comparator<Query>() {
@Override
// 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.
public int 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;
}
});
// 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, x = q[i].x;
while (currR <= R) {
add(currR, a);
currR++;
}
while (currL > L) {
add(currL - 1, a);
currL--;
}
while (currR > R + 1) {
remove(currR - 1, a);
currR--;
}
while (currL < L) {
remove(currL, a);
currL++;
}
System.out.println("query[" + L + ", " + R + ", " + x + "] : " + getans(x));
}
}
public static void main(String[] args) {
int arr[] = { 2, 0, 3, 1, 4, 2, 5, 11 };
int n = arr.length;
blk_sz = (int)Math.sqrt(n);
Query q[] ={new Query(0,2,2),new Query(0,3,5),new Query(5,7,10)};
int m = q.length;
queryResults(arr,n,q,m);
}
}
// This code is contributed by anskalyan3
Python3
# Python equivalent
MAX = 100001
SQRSIZE = 400
# Variable to represent block size.
# This is made global so compare()
# of sort can use it.
query_blk_sz = 0
# Frequency array
# to keep count of elements
frequency = [0] * MAX
# Array which contains the frequency
# of a particular block
blocks = [0] * SQRSIZE
blk_sz = 0
# class to represent a
# query range
class Query:
def __init__(self, a, b, c):
self.L = a
self.R = b
self.x = c
# 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(k):
ans = 0
left_blk, right_blk = 0, getblocknumber(k)
# If left block is equal to
# right block then we can traverse
# that block
if left_blk == right_blk:
for i in range(0, k+1):
ans += frequency[i]
else:
# Traversing first block in
# range
for i in range(0, (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, k+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):
query_blk_sz = int(m ** 0.5)
q.sort(key = lambda x: (x.L // query_blk_sz, x.R))
# Initialize current L,
# current R and current result
currL = 0
currR = 0
for i in range(m):
# L and R values of the
# current range
L = q[i].L
R = q[i].R
x = q[i].x
while currR <= R:
add(currR, a)
currR += 1
while currL > L:
add(currL - 1, a)
currL -= 1
while currR > R + 1:
remove(currR - 1, a)
currR -= 1
while currL < L:
remove(currL, a)
currL += 1
print("query[{}, {}, {}] : {}".format(L, R, x, getans(x)))
def main():
global blk_sz
arr = [2, 0, 3, 1, 4, 2, 5, 11]
n = len(arr)
blk_sz = int(n ** 0.5)
q = [Query(0,2,2),Query(0,3,5),Query(5,7,10)]
m = len(q)
queryResults(arr,n,q,m)
if __name__ == "__main__":
main()
C#
using System;
using System.Collections.Generic;
class GFG {
static int MAX = 100001;
static int SQRSIZE = 400;
// Variable to represent block size.
// This is made global so compare()
// of sort can use it.
static int query_blk_sz;
// 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];
static int blk_sz;
// class to represent a
// query range
public class Query {
public int L;
public int R;
public int x;
public Query(int a, int b, int c)
{
L = a;
R = b;
x = c;
}
}
// 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 k)
{
int ans = 0;
int left_blk, right_blk;
left_blk = 0;
right_blk = getblocknumber(k);
// If left block is equal to
// right block then we can traverse
// that block
if (left_blk == right_blk) {
for (int i = 0; i <= k; i++) {
ans += frequency[i];
}
}
else {
// Traversing first block in
// range
for (int i = 0; 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 <= k; 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)
{
query_blk_sz = (int)Math.Sqrt(m);
Array.Sort(q, new Comparison<Query>((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, x = q[i].x;
while (currR <= R) {
add(currR, a);
currR++;
}
while (currL > L) {
add(currL - 1, a);
currL--;
}
while (currR > R + 1) {
remove(currR - 1, a);
currR--;
}
while (currL < L) {
remove(currL, a);
currL++;
}
Console.WriteLine("query[" + L + ", " + R + ", "
+ x + "] : " + getans(x));
}
}
// Driver code
static void Main(string[] args)
{
int[] arr = { 2, 0, 3, 1, 4, 2, 5, 11 };
int n = arr.Length;
blk_sz = (int)Math.Sqrt(n);
Query[] q
= { new Query(0, 2, 2), new Query(0, 3, 5),
new Query(5, 7, 10) };
int m = q.Length;
// Function call
queryResults(arr, n, q, m);
}
}
// This code is contributed by phasing17
JavaScript
const MAX = 100001;
const SQRSIZE = 400;
let query_blk_sz = 0;
let frequency = new Array(MAX).fill(0);
let blocks = new Array(SQRSIZE).fill(0);
let blk_sz = 0;
class Query {
constructor(a, b, c) {
this.L = a;
this.R = b;
this.x = c;
}
}
function getblocknumber(ind) {
return Math.floor(ind / blk_sz);
}
function getans(k) {
let ans = 0;
let left_blk = 0;
let right_blk = getblocknumber(k);
if (left_blk == right_blk) {
for (let i = 0; i <= k; i++) {
ans += frequency[i];
}
} else {
for (let i = 0; i <= (left_blk + 1) * blk_sz - 1; i++) {
ans += frequency[i];
}
for (let i = left_blk + 1; i <= right_blk - 1; i++) {
ans += blocks[i];
}
for (let i = right_blk * blk_sz; i <= k; i++) {
ans += frequency[i];
}
}
return ans;
}
function add(ind, a) {
frequency[a[ind]]++;
let block_num = getblocknumber(a[ind]);
blocks[block_num]++;
}
function remove(ind, a) {
frequency[a[ind]]--;
let block_num = getblocknumber(a[ind]);
blocks[block_num]--;
}
function queryResults(a, n, q, m) {
query_blk_sz = Math.floor(Math.sqrt(m));
q.sort((a, b) => {
return a.L / query_blk_sz - b.L / query_blk_sz || a.R - b.R;
});
let currL = 0;
let currR = 0;
for (let i = 0; i < m; i++) {
let L = q[i].L;
let R = q[i].R;
let x = q[i].x;
while (currR <= R) {
add(currR, a);
currR++;
}
while (currL > L) {
add(currL - 1, a);
currL--;
}
while (currR > R + 1) {
remove(currR - 1, a);
currR--;
}
while (currL < L) {
remove(currL, a);
currL++;
}
console.log(`query[${L}, ${R}, ${x}] : ${getans(x)}`);
}
}
function main() {
let arr = [2, 0, 3, 1, 4, 2, 5, 11];
let n = arr.length;
blk_sz = Math.floor(Math.sqrt(n));
let q = [new Query(0, 2, 2), new Query(0, 3, 5), new Query(5, 7, 10)];
let m = q.length;
queryResults(arr, n, q, m);
}
main();
Output: query[0, 2, 2] : 2
query[0, 3, 5] : 4
query[5, 7, 10] : 2
Time Complexity: O(Q × ?N).
It takes O(Q × ?N) time for MO's algorithm and O(Q × ?N) time for sqrt decomposition technique to answer the sum of freq[0]+....freq[k], therefore total time complexity is O(Q × ?N + Q × ?N) which is O(Q × ?N).
Space Complexity: O(N + sqrt(N) + M), where N is the size of the input array, M is the number of queries, and sqrt(N) is the size of the blocks used in the sqrt decomposition technique.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem