The Wayback Machine - https://web.archive.org/web/20240818163937/https://www.geeksforgeeks.org/mos-algorithm-query-square-root-decomposition-set-1-introduction/
Open In App

MO’s Algorithm (Query Square Root Decomposition) | Set 1 (Introduction)

Last Updated : 19 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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
Recommended Practice

A Naive Solution is 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


Python3




# 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

Time Complexity: O(mn).
Auxiliary Space: O(1), since no extra space has been taken.

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. 

  1. 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.
  2. 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 * ?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 * ?n) + O(m * ?n) = O((m+n) * ?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


Python3




# 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: 

  1. All queries are known beforehead so that they can be preprocessed
  2. It cannot work for problems where we have update operations also mixed with sum queries.
  3. 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 * ?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/

 



Previous Article
Next Article

Similar Reads

Range Minimum Query (Square Root Decomposition and Sparse Table)
We have an array arr[0 . . . n-1]. We should be able to efficiently find the minimum value from index L (query start) to R (query end) where 0 &lt;= L &lt;= R &lt;= n-1. Consider a situation when there are many range queries. Example: Input: arr[] = {7, 2, 3, 0, 5, 10, 3, 12, 18}; query[] = [0, 4], [4, 7], [7, 8]Output: Minimum of [0, 4] is 0 Minim
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 sqrt(N) Follow the below steps to solve the probl
15+ min read
Sqrt (or Square Root) Decomposition | Set 2 (LCA of Tree in O(sqrt(height)) time)
Prerequisite: Introduction and DFSThe task is to find LCA of two given nodes in a tree (not necessarily a Binary Tree). In previous posts, we have seen how to calculate LCA using the Sparse Matrix DP approach. In this post, we will see an optimization done on the Naive method by sqrt decomposition technique that works well over the Naive Approach.
15+ min read
Cholesky Decomposition : Matrix Decomposition
In linear algebra, a matrix decomposition or matrix factorization is a factorization of a matrix into a product of matrices. There are many different matrix decompositions. One of them is Cholesky Decomposition. The Cholesky decomposition or Cholesky factorization is a decomposition of a Hermitian, positive-definite matrix into the product of a low
9 min read
Digital Root (repeated digital sum) of square of an integer using Digital root of the given integer
Given an integer N, the task is to find the digital root N2 using the digital root of N. Digital Root of a positive integer is calculated by adding the digits of the integer. If the resultant value is a single digit, then that digit is the digital root. If the resultant value contains two or more digits, those digits are summed and the process is r
6 min read
Find Square Root under Modulo p | Set 2 (Shanks Tonelli algorithm)
Given a number ‘n’ and a prime ‘p’, find square root of n under modulo p if it exists. Examples: Input: n = 2, p = 113 Output: 62 62^2 = 3844 and 3844 % 113 = 2 Input: n = 2, p = 7 Output: 3 or 4 3 and 4 both are square roots of 2 under modulo 7 because (3*3) % 7 = 2 and (4*4) % 7 = 2 Input: n = 2, p = 5 Output: Square root doesn't exist We have di
15+ min read
Check if a number is perfect square without finding square root
Check whether a number is a perfect square or not without finding its square root. Examples: Input: n = 36 Output: Yes Input: n = 12 Output: No Recommended PracticeCheck perfect squareTry It! Method 1:The idea is to run a loop from i = 1 to floor(sqrt(n)) and then check if squaring it makes n. Below is the implementation: C/C++ Code // C++ program
9 min read
Doolittle Algorithm | LU Decomposition
Doolittle Algorithm: The Doolittle Algorithm is a method for performing LU Decomposition, where a given matrix is decomposed into a lower triangular matrix L and an upper triangular matrix U. This decomposition is widely used in solving systems of linear equations, inverting matrices, and computing determinants. LU DecompositionLet A be a square ma
11 min read
Introduction to Heavy Light Decomposition
Heavy Light decomposition (HLD) is one of the most used techniques in competitive programming. Example Problem: Let us understand Heavy-light decomposition (HLD) with the help of below example. Suppose we have an unbalanced tree (not necessarily a Binary Tree) of n nodes, and we have to perform operations on the tree to answer a number of queries,
4 min read
Find Square Root under Modulo p | Set 1 (When p is in form of 4*i + 3)
Given a number 'n' and a prime 'p', find square root of n under modulo p if it exists. It may be given that p is in the form for 4*i + 3 (OR p % 4 = 3) where i is an integer. Examples of such primes are 7, 11, 19, 23, 31, ... etc,Examples: Input: n = 2, p = 7Output: 3 or 4Explanation: 3 and 4 both are square roots of 2 under modulo 7 because (3*3)
14 min read
Smallest root of the equation x^2 + s(x)*x - n = 0, where s(x) is the sum of digits of root x.
You are given an integer n, find the smallest positive integer root of equation x, or else print -1 if no roots are found.Equation: x^2 + s(x)*x - n = 0where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system. 1 &lt;= N &lt;= 10^18 Examples: Input: N = 110 Output: 10 Explanation: x
8 min read
Find if there is a pair in root to a leaf path with sum equals to root's data
Given a binary tree, find if there is a pair in root to a leaf path such that sum of values in pair is equal to root's data. For example, in below tree there are no pairs in any root to leaf path with sum equal to root's data. The idea is based on hashing and tree traversal. The idea is similar to method 2 of array pair sum problem. Create an empty
8 min read
Sum of decomposition values of all suffixes of an Array
Given an array arr[], the task is to find the sum of the decomposition value of the suffixes subarray.Decomposition Value: The decomposition value of a subarray is the count of the partition in the subarray possible. The partition in the array at index [Tex]i [/Tex]can be done only if the elements of the array before if it less than the current ind
8 min read
Calculate sum in Diagonal Matrix Decomposition by removing elements in L-shape
Given two integers N representing the dimension of a square matrix and an integer A with which the matrix is initialized. Given another integer mod. Calculate the required sum by following the given steps: Select the product of all elements in L shape beginning from the topmost right element, add it to the sum and remove all of them from the matrix
6 min read
K-shell decomposition on Social Networks
Prerequisite: Introduction to Social Networks K-shell decomposition is the method in which we can divide nodes on the basis of the number of its degree like nodes with degree 1 in one bucket etc. Consider an example, assume there are n nodes and you apply k-shell decomposition in it. So nodes with degree 1 will be in bucket1 then we will see that a
4 min read
Centroid Decomposition of Tree
Background : What is centroid of Tree? Centroid of a Tree is a node which if removed from the tree would split it into a ‘forest’, such that any tree in the forest would have at most half the number of vertices in the original tree. Suppose there are n nodes in the tree. ‘Subtree size’ for a node is the size of the tree rooted at the node. Let S(v)
15+ min read
Implementation of Heavy Light Decomposition
We strongly recommend to refer below post as a prerequisite of this.Heavy Light Decomposition | Set 1 (Introduction)In the above post, we discussed the Heavy-light decomposition (HLD) with the help of below example. Suppose we have an unbalanced tree (not necessarily a Binary Tree) of n nodes, and we have to perform operations on the tree to answer
15+ min read
LU Decomposition
LU decomposition of a matrix is the factorization of a given square matrix into two triangular matrices, one upper triangular matrix and one lower triangular matrix, such that the product of these two matrices gives the original matrix. It was introduced by Alan Turing in 1948, who also created the Turing machine. LU Decomposition is a fundamental
7 min read
Singular Value Decomposition (SVD)
The Singular Value Decomposition (SVD) of a matrix is a factorization of that matrix into three matrices. It has some interesting algebraic properties and conveys important geometrical and theoretical insights about linear transformations. It also has some important applications in data science. In this article, I will try to explain the mathematic
6 min read
Babylonian method for square root
Algorithm: This method can be derived from (but predates) Newton–Raphson method. 1 Start with an arbitrary positive start value x (the closer to the root, the better). 2 Initialize y = 1. 3. Do following until desired approximation is achieved. a) Get the next approximation for root using average of x and y b) Set y = n/x Implementation: C/C++ Code
9 min read
Find square root of number upto given precision using binary search
Given a positive number n and precision p, find the square root of number upto p decimal places using binary search. Note : Prerequisite : Binary search Examples: Input : number = 50, precision = 3 Output : 7.071 Input : number = 10, precision = 4 Output : 3.1622 We have discussed how to compute the integral value of square root in Square Root usin
9 min read
Program to calculate Root Mean Square
Given an array of N numbers. The task is to calculate the Root Mean Square(RMS) of the given numbers. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 3.31662 Input: arr[] = {10, 4, 6, 8} Output: 7.34847 Approach: The Root Mean Square value of N numbers x1,x2,x3,.....xn can be given as, RMS method first calculates the square of each number and then
4 min read
Sum of elements whose square root is present in the array
Given an array arr[], the task is to find the sum of all those elements from the given array whose square root is present in the same array. Examples: Input: arr[] = {1, 2, 3, 4, 6, 9, 10} Output: 13 4 and 9 are the only numbers whose square roots 2 and 3 are present in the array Input: arr[] = {4, 2, 36, 6, 10, 100} Output: 140 Naive Approach: To
10 min read
Range Sum Queries and Update with Square Root
Given an array A of N integers and number of queries Q. You have to answer two types of queries. Update [l, r] – for every i in range from l to r update Ai with sqrt(Ai), where sqrt(Ai) represents the square root of Ai in integral form.Query [l, r] – calculate the sum of all numbers ranging between l and r in array A. Prerequisite: Binary Indexed T
13 min read
Square root of a number without using sqrt() function
Given a number N, the task is to find the square root of N without using sqrt() function. Examples: Input: N = 25 Output: 5 Input: N = 3 Output: 1.73205 Input: N = 2.5 Output: 1.58114 Approach 1: We can consider (?x-?x)2 = 0.Replacing one of the ?x's with y, then the equation becomes (y-?x)2 =&gt; y2 - 2y?x + x = 0=&gt; ?x = (y2 + x) / 2y=&gt; ?x =
14 min read
Floor square root without using sqrt() function : Recursive
Given a number N, the task is to find the floor square root of the number N without using the built-in square root function. Floor square root of a number is the greatest whole number which is less than or equal to its square root. Examples: Input: N = 25 Output: 5 Explanation: Square root of 25 = 5. Therefore 5 is the greatest whole number less th
7 min read
Long Division Method to find Square root with Examples
Given an integer X which is a perfect square, the task is to find the square root of it by using the long division method. Examples: Input: N = 484 Output: 22 222 = 484 Input: N = 144 Output: 12 122 = 144 Approach: Long division is a very common method to find the square root of a number. The following is the stepwise solution for this method: 1. D
10 min read
Min operations to reduce N by multiplying by any number or taking square root
Given a number N, the task is to find the minimum value of N by applying below operations any number of times: Multiply N by any positive integerReplace N with sqrt(N), only if N is a perfect square. Examples: Input: N = 20 Output: 10Explanation: Multiply -&gt; 20 * 5 = 100 sqrt(100) = 10, which is the minimum value obtainable. Input: N = 5184 Outp
4 min read
Square root of two Complex Numbers
Given two positive integers A and B representing the complex number Z in the form of Z = A + i * B, the task is to find the square root of the given complex number. Examples: Input: A = 0, B =1Output:The Square roots are: 0.707107 + 0.707107*i-0.707107 - 0.707107*i Input: A = 4, B = 0Output:The Square roots are: 2-2 Approach: The given problem can
9 min read
Proof: Why the Root Mean Square of two positive numbers is always greater than their Geometric Mean?
This article focuses on discussing the proof of why the root-mean-square of two positive numbers is always greater than their geometric mean. Before getting into the details of the proof, let's first discuss the basic terminologies: Root Mean Square (RMS):Consider some numbers, A1, A2, A3, A4, .... AN, the root-mean-square of these numbers will be
3 min read
Practice Tags :
three90RightbarBannerImg