MO’s Algorithm (Query Square Root Decomposition) | Set 1 (Introduction)
Last Updated :
27 Feb, 2025
Let us consider the following problem to understand MO’s Algorithm.
We are given an array and a set of query ranges, we are required to find the sum of every query range.
Example:
Input: arr[] = {1, 1, 2, 1, 3, 4, 5, 2, 8};
query[] = [0, 4], [1, 3] [2, 4]
Output: Sum of arr[] elements in range [0, 4] is 8
Sum of arr[] elements in range [1, 3] is 4
Sum of arr[] elements in range [2, 4] is 6
[Naive Solution] – Linearly Compute Sum for Every Query – O(mn) Time and O(1) Space
The idea s to run a loop from L to R and calculate the sum of elements in given range for every query [L, R]
C++
// C++ Program to compute sum of ranges for different range
// queries.
#include <bits/stdc++.h>
using namespace std;
// Structure to represent a query range
struct Query
{
int L, R;
};
// Prints sum of all query ranges. m is number of queries
// n is the size of the array.
void printQuerySums(int a[], int n, Query q[], int m)
{
// One by one compute sum of all queries
for (int i=0; i<m; i++)
{
// Left and right boundaries of current range
int L = q[i].L, R = q[i].R;
// Compute sum of current query range
int sum = 0;
for (int j=L; j<=R; j++)
sum += a[j];
// Print sum of current query range
cout << "Sum of [" << L << ", "
<< R << "] is " << sum << endl;
}
}
// Driver program
int main()
{
int a[] = {1, 1, 2, 1, 3, 4, 5, 2, 8};
int n = sizeof(a)/sizeof(a[0]);
Query q[] = {{0, 4}, {1, 3}, {2, 4}};
int m = sizeof(q)/sizeof(q[0]);
printQuerySums(a, n, q, m);
return 0;
}
Java
// Java Program to compute sum of ranges for different range
// queries.
import java.util.*;
// Class to represent a query range
class Query{
int L;
int R;
Query(int L, int R){
this.L = L;
this.R = R;
}
}
class GFG
{
// Prints sum of all query ranges. m is number of queries
// n is the size of the array.
static void printQuerySums(int a[], int n, ArrayList<Query> q, int m)
{
// One by one compute sum of all queries
for (int i=0; i<m; i++)
{
// Left and right boundaries of current range
int L = q.get(i).L, R = q.get(i).R;
// Compute sum of current query range
int sum = 0;
for (int j=L; j<=R; j++)
sum += a[j];
// Print sum of current query range
System.out.println("Sum of [" + L +
", " + R + "] is " + sum);
}
}
// Driver program
public static void main(String argv[])
{
int a[] = {1, 1, 2, 1, 3, 4, 5, 2, 8};
int n = a.length;
ArrayList<Query> q = new ArrayList<Query>();
q.add(new Query(0,4));
q.add(new Query(1,3));
q.add(new Query(2,4));
int m = q.size();
printQuerySums(a, n, q, m);
}
}
// This code is contributed by shivanisinghss2110
Python
# Python program to compute sum of ranges for different range queries.
# Function that accepts array and list of queries and print sum of each query
def printQuerySum(arr,Q):
for q in Q: # Traverse through each query
L,R = q # Extract left and right indices
s = 0
for i in range(L,R+1): # Compute sum of current query range
s += arr[i]
print("Sum of",q,"is",s) # Print sum of current query range
# Driver script
arr = [1, 1, 2, 1, 3, 4, 5, 2, 8]
Q = [[0, 4], [1, 3], [2, 4]]
printQuerySum(arr,Q)
#This code is contributed by Shivam Singh
C#
// C# program to compute sum of ranges for
// different range queries
using System;
using System.Collections;
// Class to represent a query range
public class Query
{
public int L;
public int R;
public Query(int L, int R)
{
this.L = L;
this.R = R;
}
}
class GFG{
// Prints sum of all query ranges. m
//is number of queries n is the size
// of the array.
static void printQuerySums(int []a, int n,
ArrayList q, int m)
{
// One by one compute sum of all queries
for(int i = 0; i < m; i++)
{
// Left and right boundaries of
// current range
int L = ((Query)q[i]).L,
R = ((Query)q[i]).R;
// Compute sum of current query range
int sum = 0;
for(int j = L; j <= R; j++)
sum += a[j];
// Print sum of current query range
Console.Write("Sum of [" + L + ", " +
R + "] is " + sum + "\n");
}
}
// Driver code
public static void Main(string []argv)
{
int []a = { 1, 1, 2, 1, 3, 4, 5, 2, 8 };
int n = a.Length;
ArrayList q = new ArrayList();
q.Add(new Query(0, 4));
q.Add(new Query(1, 3));
q.Add(new Query(2, 4));
int m = q.Count;
printQuerySums(a, n, q, m);
}
}
// This code is contributed by pratham76
JavaScript
<script>
// Javascript Program to compute sum of ranges for different range
// queries.
// Class to represent a query range
class Query{
constructor(L, R)
{
this.L = L;
this.R = R;
}
}
// Prints sum of all query ranges. m is number of queries
// n is the size of the array.
function printQuerySums(a, n, q, m)
{
// One by one compute sum of all queries
for (let i = 0; i < m; i++)
{
// Left and right boundaries of current range
let L = q[i].L, R = q[i].R;
// Compute sum of current query range
let sum = 0;
for (let j = L; j <= R; j++)
sum += a[j];
// Print sum of current query range
document.write("Sum of [" + L +
", " + R + "] is " + sum+"<br>");
}
}
// Driver program
let a = [1, 1, 2, 1, 3, 4, 5, 2, 8];
let n = a.length;
let q = [];
q.push(new Query(0,4));
q.push(new Query(1,3));
q.push(new Query(2,4));
let m = q.length;
printQuerySums(a, n, q, m);
// This code is contributed by avanitrachhadiya2155
</script>
Output:
Sum of [0, 4] is 8
Sum of [1, 3] is 4
Sum of [2, 4] is 6
[Expected Solution] – MO’s algorithm – Preprocess Queries
The idea of MO’s algorithm is to pre-process all queries so that result of one query can be used in next query. Below are steps.
Let a[0…n-1] be input array and q[0..m-1] be 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 sum computed in the previous query.
- Let ‘sum’ be sum of previous query.
- Remove extra elements of previous query. For example if previous query is [0, 8] and current query is [3, 9], then we subtract a[0],a[1] and a[2] from sum
- Add new elements of current query. In the same example as above, we add a[9] to sum.
The great thing about this algorithm is, in step 2, index variable for R change at most O(n * ?n) times throughout the run and same for L changes its value at most O(m * sqrt(n)) times (See below, after the code, for details). All these bounds are possible only because the queries are sorted first in blocks of ?n size.
The preprocessing part takes O(m Log m) time.
Processing all queries takes O(n * sqrt(n)) + O(m * sqrt(n)) = O((m+n) * sqrt(n)) time.
Below is the implementation of the above idea.
C++
// Program to compute sum of ranges for different range
// queries
#include <bits/stdc++.h>
using namespace std;
// Variable to represent block size. This is made global
// so compare() of sort can use it.
int block;
// Structure to represent a query range
struct Query
{
int L, R;
};
// 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)
{
// Different blocks, sort by block.
if (x.L/block != y.L/block)
return x.L/block < y.L/block;
// Same block, sort by R value
return x.R < y.R;
}
// Prints sum of all query ranges. m is number of queries
// n is size of array a[].
void queryResults(int a[], int n, Query q[], int m)
{
// Find block size
block = (int)sqrt(n);
// Sort all queries so that queries of same blocks
// are arranged together.
sort(q, q + m, compare);
// Initialize current L, current R and current sum
int currL = 0, currR = 0;
int currSum = 0;
// Traverse through all queries
for (int i=0; i<m; i++)
{
// L and R values of current range
int L = q[i].L, R = q[i].R;
// Remove extra elements of previous range. For
// example if previous range is [0, 3] and current
// range is [2, 5], then a[0] and a[1] are subtracted
while (currL < L)
{
currSum -= a[currL];
currL++;
}
// Add Elements of current Range
while (currL > L)
{
currSum += a[currL-1];
currL--;
}
while (currR <= R)
{
currSum += a[currR];
currR++;
}
// Remove elements of previous range. For example
// when previous range is [0, 10] and current range
// is [3, 8], then a[9] and a[10] are subtracted
while (currR > R+1)
{
currSum -= a[currR-1];
currR--;
}
// Print sum of current range
cout << "Sum of [" << L << ", " << R
<< "] is " << currSum << endl;
}
}
// Driver program
int main()
{
int a[] = {1, 1, 2, 1, 3, 4, 5, 2, 8};
int n = sizeof(a)/sizeof(a[0]);
Query q[] = {{0, 4}, {1, 3}, {2, 4}};
int m = sizeof(q)/sizeof(q[0]);
queryResults(a, n, q, m);
return 0;
}
Java
// Java Program to compute sum of ranges for
// different range queries
import java.util.*;
// Class to represent a query range
class Query{
int L;
int R;
Query(int L, int R){
this.L = L;
this.R = R;
}
}
class MO{
// Prints sum of all query ranges. m is number of queries
// n is size of array a[].
static void queryResults(int a[], int n, ArrayList<Query> q, int m){
// Find block size
int block = (int) Math.sqrt(n);
// Sort all queries so that queries of same blocks
// are arranged together.
Collections.sort(q, new Comparator<Query>(){
// 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){
// Different blocks, sort by block.
if (x.L/block != y.L/block)
return (x.L < y.L ? -1 : 1);
// Same block, sort by R value
return (x.R < y.R ? -1 : 1);
}
});
// Initialize current L, current R and current sum
int currL = 0, currR = 0;
int currSum = 0;
// Traverse through all queries
for (int i=0; i<m; i++)
{
// L and R values of current range
int L = q.get(i).L, R = q.get(i).R;
// Remove extra elements of previous range. For
// example if previous range is [0, 3] and current
// range is [2, 5], then a[0] and a[1] are subtracted
while (currL < L)
{
currSum -= a[currL];
currL++;
}
// Add Elements of current Range
while (currL > L)
{
currSum += a[currL-1];
currL--;
}
while (currR <= R)
{
currSum += a[currR];
currR++;
}
// Remove elements of previous range. For example
// when previous range is [0, 10] and current range
// is [3, 8], then a[9] and a[10] are subtracted
while (currR > R+1)
{
currSum -= a[currR-1];
currR--;
}
// Print sum of current range
System.out.println("Sum of [" + L +
", " + R + "] is " + currSum);
}
}
// Driver program
public static void main(String argv[]){
ArrayList<Query> q = new ArrayList<Query>();
q.add(new Query(0,4));
q.add(new Query(1,3));
q.add(new Query(2,4));
int a[] = {1, 1, 2, 1, 3, 4, 5, 2, 8};
queryResults(a, a.length, q, q.size());
}
}
// This code is contributed by Ajay
Python
# Python program to compute sum of ranges for different range queries
import math
# Function that accepts array and list of queries and print sum of each query
def queryResults(arr,Q):
#Q.sort(): # Sort by L
#sort all queries so that all queries in the increasing order of R values .
Q.sort(key=lambda x: x[1])
# Initialize current L, current R and current sum
currL,currR,currSum = 0,0,0
# Traverse through all queries
for i in range(len(Q)):
L,R = Q[i] # L and R values of current range
# Remove extra elements from previous range
# if previous range is [0, 3] and current
# range is [2, 5], then a[0] and a[1] are subtracted
while currL<L:
currSum-=arr[currL]
currL+=1
# Add elements of current range
while currL>L:
currSum+=arr[currL-1]
currL-=1
while currR<=R:
currSum+=arr[currR]
currR+=1
# Remove elements of previous range
# when previous range is [0, 10] and current range
# is [3, 8], then a[9] and a[10] are subtracted
while currR>R+1:
currSum-=arr[currR-1]
currR-=1
# Print the sum of current range
print("Sum of",Q[i],"is",currSum)
arr = [1, 1, 2, 1, 3, 4, 5, 2, 8]
Q = [[0, 4], [1, 3], [2, 4]]
queryResults(arr,Q)
#This code is contributed by Shivam Singh
C#
// C# Program to compute sum of ranges for different range
// queries
using System;
using System.Collections.Generic;
class GFG
{
// Variable to represent block size. This is made global
// so compare() of sort can use it.
public static int block;
// Structure to represent a query range
public struct Query
{
public int L;
public int R;
public Query(int l, int r)
{
L = l;
R = r;
}
}
// 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 class Comparer : IComparer<Query> {
public int Compare(Query x, Query y)
{
int ret = (int)(x.L / block)
.CompareTo((int)(y.L / block));
return ret != 0 ? ret : x.R.CompareTo(y.R);
}
}
// Prints sum of all query ranges. m is number of
// queries n is size of array a[].
static void queryResults(int[] a, int n, List<Query> q,
int m)
{
// Find block size
block = (int)(Math.Sqrt(n));
// Sort all queries so that queries of same blocks
// are arranged together.
q.Sort(new Comparer());
// Initialize current L, current R and current sum
int currL = 0, currR = 0;
int currSum = 0;
// Traverse through all queries
for (int i = 0; i < m; i++) {
// L and R values of current range
int L = q[i].L, R = q[i].R;
// Remove extra elements of previous range. For
// example if previous range is [0, 3] and
// current range is [2, 5], then a[0] and a[1]
// are subtracted
while (currL < L) {
currSum -= a[currL];
currL++;
}
// Add Elements of current Range
while (currL > L) {
currSum += a[currL - 1];
currL--;
}
while (currR <= R) {
currSum += a[currR];
currR++;
}
// Remove elements of previous range. For
// example when previous range is [0, 10] and
// current range is [3, 8], then a[9] and a[10]
// are subtracted
while (currR > R + 1) {
currSum -= a[currR - 1];
currR--;
}
// Print sum of current range
Console.WriteLine("Sum of [{0}, {1}] is {2}", L,
R, currSum);
}
}
// Driver program
static void Main(string[] args)
{
int[] a = { 1, 1, 2, 1, 3, 4, 5, 2, 8 };
int n = a.Length;
List<Query> q = new List<Query>();
q.Add(new Query(0, 4));
q.Add(new Query(1, 3));
q.Add(new Query(2, 4));
int m = q.Count;
queryResults(a, n, q, m);
}
}
// This code is contributed by cavi4762.
JavaScript
// JavaScript program to compute sum of ranges for different range queries
// Function that accepts array and list of queries and print sum of each query
function queryResults(arr, Q) {
// Sort all queries so that all queries in the increasing order of R values
Q.sort((a, b) => a[1] - b[1]);
// Initialize current L, current R and current sum
let currL = 0;
let currR = 0;
let currSum = 0;
// Traverse through all queries
for (let i = 0; i < Q.length; i++) {
const L = Q[i][0];
const R = Q[i][1];
// Remove extra elements from previous range
// if previous range is [0, 3] and current
// range is [2, 5], then a[0] and a[1] are subtracted
while (currL < L) {
currSum -= arr[currL];
currL++;
}
// Add elements of current range
while (currL > L) {
currSum += arr[currL - 1];
currL--;
}
while (currR <= R) {
currSum += arr[currR];
currR++;
}
// Remove elements of previous range
// when previous range is [0, 10] and current range
// is [3, 8], then a[9] and a[10] are subtracted
while (currR > R + 1) {
currSum -= arr[currR - 1];
currR--;
}
// Print the sum of current range
console.log(`Sum of ${Q[i]} is ${currSum}`);
}
}
const arr = [1, 1, 2, 1, 3, 4, 5, 2, 8];
const Q = [[1, 3], [0, 4], [2, 4]];
queryResults(arr, Q);
Output:
Sum of [1, 3] is 4
Sum of [0, 4] is 8
Sum of [2, 4] is 6
The output of above program doesn’t print results of queries in same order as input, because queries are sorted. The program can be easily extended to keep the same order.
Important Observations:
- All queries are known beforehead so that they can be preprocessed
- It cannot work for problems where we have update operations also mixed with sum queries.
- MO’s algorithm can only be used for query problems where a query can be computed from results of the previous query. One more such example is maximum or minimum.
Time Complexity Analysis:
The function mainly runs a for loop for all sorted queries. Inside the for loop, there are four while queries that move ‘currL’ and ‘currR’.
How much currR is moved? For each block, queries are sorted in increasing order of R. So, for a block, currR moves in increasing order. In worst case, before beginning of every block, currR at extreme right and current block moves it back the extreme left. This means that for every block, currR moves at most O(n). Since there are O(?n) blocks, total movement of currR is O(n * sqrt(n)).
How much currL is moved? Since all queries are sorted in a way that L values are grouped by blocks, movement is O(?n) when we move from one query to another quert. For m queries, total movement of currL is O(m * ?n)
Please note that a Simple and more Efficient solution to solve this problem is to compute prefix sum for all elements from 0 to n-1. Let the prefix sum be stored in an array preSum[] (The value of preSum[i] stores sum of arr[0..i]). Once we have built preSum[], we can traverse through all queries one by one. For every query [L, R], we return value of preSum[R] – preSum[L]. Here processing every query takes O(1) time.
Auxiliary Space: O(1), since no extra space has been taken.
The idea of this article is to introduce MO’s algorithm with a very simple example. We will soon be discussing more interesting problems using MO’s algorithm.
Range Minimum Query (Square Root Decomposition and Sparse Table)
References:
http://blog.anudeep2011.com/mos-algorithm/
Similar Reads
Array Data Structure
Complete Guide to ArraysLearn more about Array in DSA Self Paced CoursePractice Problems on ArraysTop Quizzes on Arrays What is Array?An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calcul
3 min read
What is Array?
Array is a linear data structure where all elements are arranged sequentially. It is a collection of elements of same data type stored at contiguous memory locations. For simplicity, we can think of an array as a flight of stairs where on each step is placed a value (let's say one of your friends).
2 min read
Getting Started with Array Data Structure
Array is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
Applications, Advantages and Disadvantages of Array
Array is a linear data structure that is a collection of data elements of same types. Arrays are stored in contiguous memory locations. It is a static data structure with a fixed size. Table of Content Applications of Array Data Structure:Advantages of Array Data Structure:Disadvantages of Array Dat
2 min read
Subarrays, Subsequences, and Subsets in Array
What is a Subarray?A subarray is a contiguous part of array, i.e., Subarray is an array that is inside another array. In general, for an array of size n, there are n*(n+1)/2 non-empty subarrays. For example, Consider the array [1, 2, 3, 4], There are 10 non-empty sub-arrays. The subarrays are: (1),
10 min read
Basic operations in Array
Searching in Array
Searching is one of the most common operations performed in an array. Array searching can be defined as the operation of finding a particular element or a group of elements in the array. There are several searching algorithms. The most commonly used among them are: Linear Search Binary Search Ternar
4 min read
Array Reverse - Complete Tutorial
Given an array arr[], the task is to reverse the array. Reversing an array means rearranging the elements such that the first element becomes the last, the second element becomes second last and so on. Examples: Input: arr[] = {1, 4, 3, 2, 6, 5} Output: {5, 6, 2, 3, 4, 1}Explanation: The first eleme
15+ min read
Rotate an Array by d - Counterclockwise or Left
Given an array of integers arr[] of size n, the task is to rotate the array elements to the left by d positions. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6}, d = 2Output: {3, 4, 5, 6, 1, 2}Explanation: After first left rotation, arr[] becomes {2, 3, 4, 5, 6, 1} and after the second rotation, arr[] b
15+ min read
Print array after it is right rotated K times
Given an Array of size N and a value K, around which we need to right rotate the array. How do you quickly print the right rotated array?Examples : Input: Array[] = {1, 3, 5, 7, 9}, K = 2.Output: 7 9 1 3 5Explanation:After 1st rotation - {9, 1, 3, 5, 7}After 2nd rotation - {7, 9, 1, 3, 5} Input: Arr
15+ min read
Search, Insert, and Delete in an Unsorted Array | Array Operations
In this post, a program to search, insert, and delete operations in an unsorted array is discussed. Search Operation:In an unsorted array, the search operation can be performed by linear traversal from the first element to the last element. Coding implementation of the search operation:[GFGTABS] C++
15+ min read
Search, Insert, and Delete in an Sorted Array | Array Operations
How to Search in a Sorted Array?In a sorted array, the search operation can be performed by using binary search. Below is the implementation of the above approach: [GFGTABS] C++ // C++ program to implement binary search in sorted array #include <bits/stdc++.h> using namespace std; int binarySe
15+ min read
Array Sorting - Practice Problems
Sorting an array means arranging the elements of the array in a certain order. Generally sorting in an array is done to arrange the elements in increasing or decreasing order. Problem statement: Given an array of integers arr, the task is to sort the array in ascending order and return it, without u
9 min read
Generating All Subarrays
Given an array arr[], the task is to generate all the possible subarrays of the given array. Examples: Input: arr[] = [1, 2, 3]Output: [ [1], [1, 2], [2], [1, 2, 3], [2, 3], [3] ]Input: arr[] = [1, 2]Output: [ [1], [1, 2], [2] ] Iterative ApproachTo generate a subarray, we need a starting index from
8 min read
Easy problems on Array
Largest three distinct elements in an array
Given an array arr[], the task is to find the top three largest distinct integers present in the array. Note: If there are less than three distinct elements in the array, then return the available distinct numbers in descending order. Examples : Input: arr[] = [10, 4, 3, 50, 23, 90]Output: [90, 50,
6 min read
Second Largest Element in an Array
Given an array of positive integers arr[] of size n, the task is to find second largest distinct element in the array. Note: If the second largest element does not exist, return -1. Examples: Input: arr[] = [12, 35, 1, 10, 34, 1]Output: 34Explanation: The largest element of the array is 35 and the s
14 min read
Move all zeros to end of array
Given an array of integers arr[], the task is to move all the zeros to the end of the array while maintaining the relative order of all non-zero elements. Examples: Input: arr[] = [1, 2, 0, 4, 3, 0, 5, 0]Output: arr[] = [1, 2, 4, 3, 5, 0, 0, 0]Explanation: There are three 0s that are moved to the en
15 min read
Rearrange array such that even positioned are greater than odd
Given an array arr[], sort the array according to the following relations: arr[i] >= arr[i - 1], if i is even, â 1 <= i < narr[i] <= arr[i - 1], if i is odd, â 1 <= i < nFind the resultant array.[consider 1-based indexing] Examples: Input: arr[] = [1, 2, 2, 1]Output: [1 2 1 2] Expl
9 min read
Rearrange an array in maximum minimum form using Two Pointer Technique
Given a sorted array of positive integers, rearrange the array alternately i.e first element should be a maximum value, at second position minimum value, at third position second max, at fourth position second min, and so on. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: arr[] = {7, 1, 6, 2
6 min read
Segregate even and odd numbers using Lomutoâs Partition Scheme
Given an array arr[] of integers, segregate even and odd numbers in the array such that all the even numbers should be present first, and then the odd numbers. Examples: Input: arr[] = {7, 2, 9, 4, 6, 1, 3, 8, 5}Output: 2 4 6 8 7 9 1 3 5 Input: arr[] = {1, 3, 2, 4, 7, 6, 9, 10}Output: 2 4 6 10 7 1 9
7 min read
Reversal algorithm for Array rotation
Given an array arr[] of size N, the task is to rotate the array by d position to the left. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7}, d = 2Output: 3, 4, 5, 6, 7, 1, 2Explanation: If the array is rotated by 1 position to the left, it becomes {2, 3, 4, 5, 6, 7, 1}.When it is rotated further by 1
15 min read
Print left rotation of array in O(n) time and O(1) space
Given an array of size n and multiple values around which we need to left rotate the array. How to quickly print multiple left rotations? Examples : Input : arr[] = {1, 3, 5, 7, 9}k1 = 1k2 = 3k3 = 4k4 = 6Output : 3 5 7 9 17 9 1 3 59 1 3 5 73 5 7 9 1Input : arr[] = {1, 3, 5, 7, 9}k1 = 14 Output : 9 1
15+ min read
Sort an array which contain 1 to n values
We are given an array that contains 1 to n elements, our task is to sort this array in an efficient way. We are not allowed to simply copy the numbers from 1 to n.Examples : Input : arr[] = {2, 1, 3};Output : {1, 2, 3} Input : arr[] = {2, 1, 4, 3};Output : {1, 2, 3, 4} Native approach - O(n Log n) T
7 min read
Count Possible Triangles
Given an unsorted array of positive integers, the task is to find the number of triangles that can be formed with three different array elements as three sides of triangles. For a triangle to be possible from 3 values as sides, the sum of the two values (or sides) must always be greater than the thi
15+ min read
Print all Distinct (Unique) Elements in given Array
Given an integer array arr[], print all distinct elements from this array. The given array may contain duplicates and the output should contain every element only once. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}Output: {12, 10, 9, 45, 2} Input: arr[] = {1, 2, 3, 4, 5}Output: {1, 2, 3, 4
11 min read
Unique Number I
Given an array of integers, every element in the array appears twice except for one element which appears only once. The task is to identify and return the element that occurs only once. Examples: Input: arr[] = [2, 3, 5, 4, 5, 3, 4]Output: 2 Explanation: Since 2 occurs once, while other numbers occ
9 min read
Leaders in an array
Given an array arr[] of size n, the task is to find all the Leaders in the array. An element is a Leader if it is greater than or equal to all the elements to its right side. Note: The rightmost element is always a leader. Examples: Input: arr[] = [16, 17, 4, 3, 5, 2]Output: [17 5 2]Explanation: 17
10 min read
Subarray with Given Sum
Given a 1-based indexing array arr[] of non-negative integers and an integer sum. You mainly need to return the left and right indexes(1-based indexing) of that subarray. In case of multiple subarrays, return the subarray indexes which come first on moving from left to right. If no such subarray exi
11 min read
Intermediate problems on Array
Rearrange an array such that arr[i] = i
Given an array of elements of length n, ranging from 0 to n - 1. All elements may not be present in the array. If the element is not present then there will be -1 present in the array. Rearrange the array such that arr[i] = i and if i is not present, display -1 at that place. Examples: Input: arr[]
13 min read
Alternate Rearrangement of Positives and Negatives
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. A number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If t
11 min read
Reorder an array according to given indexes
Given two integer arrays of the same size, "arr[]" and "index[]", reorder elements in "arr[]" according to the given index array. Example: Input: arr[] = [10, 11, 12]; index[] = [1, 0, 2];Output: arr[] = [11, 10, 12] index[] = [0, 1, 2] Input: arr[] = [50, 40, 70, 60, 90] index[] = [3, 0, 4, 1, 2]Ou
15+ min read
Find the smallest missing number
Given a sorted array of n distinct integers where each integer is in the range from 0 to m-1 and m > n. Find the smallest number that is missing from the array. Examples: Input: {0, 1, 2, 6, 9}, n = 5, m = 10 Output: 3 Input: {4, 5, 10, 11}, n = 4, m = 12 Output: 0 Input: {0, 1, 2, 3}, n = 4, m =
15 min read
Difference Array | Range update query in O(1)
Consider an array A[] of integers and following two types of queries. update(l, r, x) : Adds x to all values from A[l] to A[r] (both inclusive).printArray() : Prints the current modified array. Examples : Input : A [] { 10, 5, 20, 40 } update(0, 1, 10) printArray() update(1, 3, 20) update(2, 2, 30)
8 min read
Stock Buy and Sell â Max 2 Transactions Allowed
In the stock market, a person buys a stock and sells it on some future date. Given the stock prices of n days in an array prices[ ]. Find out the maximum profit a person can make in at most 2 transactions. A transaction is equivalent to (buying + selling) of a stock and a new transaction can start o
15+ min read
Smallest subarray with sum greater than a given value
Given an array arr[] of integers and a number x, the task is to find the smallest subarray with a sum strictly greater than x. Examples: Input: x = 51, arr[] = [1, 4, 45, 6, 0, 19]Output: 3Explanation: Minimum length subarray is [4, 45, 6] Input: x = 100, arr[] = [1, 10, 5, 2, 7]Output: 0Explanation
15+ min read
Count Inversions of an Array
Given an integer array arr[] of size n, find the inversion count in the array. Two array elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j. Note: Inversion Count for an array indicates that how far (or close) the array is from being sorted. If the array is already sorte
15+ min read
Merge Two Sorted Arrays Without Extra Space
Given two sorted arrays a[] and b[] of size n and m respectively, the task is to merge both the arrays and rearrange the elements such that the smallest n elements are in a[] and the remaining m elements are in b[]. All elements in a[] and b[] should be in sorted order. Examples: Input: a[] = [2, 4,
15+ min read
Majority Element
You are given an array arr, and your task is to find the majority element an element that occurs more than half the length of the array (i.e., arr.size() / 2). If such an element exists return it, otherwise return -1, indicating that no majority element is present. Examples : Input : arr[] = [1, 1,
15+ min read
Two Pointers Technique
Two pointers is really an easy and effective technique that is typically used for Two Sum in Sorted Arrays, Closest Two Sum, Three Sum, Four Sum, Trapping Rain Water and many other popular interview questions. Given a sorted array arr (sorted in ascending order) and a target, find if there exists an
12 min read
3 Sum - Triplet Sum in Array
Given an array arr[] of size n and an integer sum, the task is to check if there is a triplet in the array which sums up to the given target sum. Examples: Input: arr[] = [1, 4, 45, 6, 10, 8], target = 13Output: true Explanation: The triplet [1, 4, 8] sums up to 13 Input: arr[] = [1, 2, 4, 3, 6, 7],
15 min read
Equilibrium Index
Given an array arr[] of size n, the task is to return an equilibrium index (if any) or -1 if no equilibrium index exists. The equilibrium index of an array is an index such that the sum of all elements at lower indexes equals the sum of all elements at higher indexes. Note: When the index is at the
15 min read
Hard problems on Array
MO's Algorithm (Query Square Root Decomposition) | Set 1 (Introduction)
Let us consider the following problem to understand MO's Algorithm. We are given an array and a set of query ranges, we are required to find the sum of every query range. Example: Input: arr[] = {1, 1, 2, 1, 3, 4, 5, 2, 8}; query[] = [0, 4], [1, 3] [2, 4]Output: Sum of arr[] elements in range [0, 4]
15+ min read
Square Root (Sqrt) Decomposition Algorithm
Square Root Decomposition Technique is one of the most common query optimization techniques used by competitive programmers. This technique helps us to reduce Time Complexity by a factor of sqrt(N) The key concept of this technique is to decompose a given array into small chunks specifically of size
15+ min read
Sparse Table
We have briefly discussed sparse table in Range Minimum Query (Square Root Decomposition and Sparse Table)Sparse table concept is used for fast queries on a set of static data (elements do not change). It does preprocessing so that the queries can be answered efficiently. Example Problem 1 : Range M
15+ min read
Range sum query using Sparse Table
We have an array arr[]. We need to find the sum of all the elements in the range L and R where 0 <= L <= R <= n-1. Consider a situation when there are many range queries. Examples: Input : 3 7 2 5 8 9 query(0, 5) query(3, 5) query(2, 4) Output : 34 22 15Note : array is 0 based indexed and q
8 min read
Range LCM Queries
Given an array arr[] of integers of size N and an array of Q queries, query[], where each query is of type [L, R] denoting the range from index L to index R, the task is to find the LCM of all the numbers of the range for all the queries. Examples: Input: arr[] = {5, 7, 5, 2, 10, 12 ,11, 17, 14, 1,
15+ min read
Jump Game - Minimum Jumps to Reach End
Given an array arr[] of non-negative numbers. Each number tells you the maximum number of steps you can jump forward from that position.For example: If arr[i] = 3, you can jump to index i + 1, i + 2, or i + 3 from position i.If arr[i] = 0, you cannot jump forward from that position.Your task is to f
15+ min read
Space optimization using bit manipulations
There are many situations where we use integer values as index in array to see presence or absence, we can use bit manipulations to optimize space in such problems.Let us consider below problem as an example.Given two numbers say a and b, mark the multiples of 2 and 5 between a and b using less than
12 min read
Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed
Given an array arr[] of size N, the task is to find the maximum possible sum of i*arr[i] when the array can be rotated any number of times. Examples : Input: arr[] = {1, 20, 2, 10}Output: 72.We can get 72 by rotating array twice.{2, 10, 1, 20}20*3 + 1*2 + 10*1 + 2*0 = 72 Input: arr[] = {10, 1, 2, 3,
12 min read
Construct an array from its pair-sum array
Given a pair-sum array construct the original array. A pair-sum array for an array is the array that contains sum of all pairs in ordered form, i.e., pair[0] is sum of arr[0] and arr[1], pair[1] is sum of arr[0] and arr[2] and so on. Note that if the size of input array is n, then the size of pair a
5 min read
Maximum equilibrium sum in an array
Given an array arr[]. Find the maximum value of prefix sum which is also suffix sum for index i in arr[]. Examples : Input : arr[] = {-1, 2, 3, 0, 3, 2, -1}Output : 4Explanation : Prefix sum of arr[0..3] = Suffix sum of arr[3..6]Input : arr[] = {-3, 5, 3, 1, 2, 6, -4, 2}Output : 7Explanation : Prefi
11 min read
Smallest Difference Triplet from Three arrays
Three arrays of same size are given. Find a triplet such that maximum - minimum in that triplet is minimum of all the triplets. A triplet should be selected in a way such that it should have one number from each of the three given arrays. If there are 2 or more smallest difference triplets, then the
10 min read
Top 50 Array Coding Problems for Interviews
Array is one of the most widely used data structure and is frequently asked in coding interviews to the problem solving skills. The following list of 50 array coding problems covers a range of difficulty levels, from easy to hard, to help candidates prepare for interviews. Easy Problems Second Large
2 min read