Skip to content
Related Articles

Related Articles

Improve Article
Levelwise Alternating GCD and LCM of nodes in Segment Tree
  • Difficulty Level : Medium
  • Last Updated : 16 Apr, 2021

A Levelwise GCD/LCM alternating segment tree is a segment tree, such that at every level the operations GCD and LCM alternate. In other words at Level 1 the left and right sub-trees combine together by the GCD operation i.e Parent node = Left Child GCD Right Child and on Level 2 the left 
and right sub-trees combine together by the LCM operation i.e Parent node = Left Child LCM Right Child
Such a type of Segment tree has the following type of structure:
 

 

The operations (GCD) and (LCM) indicate which operation was carried out to merge the child nodes
Given N leaf nodes, the task is to build such a segment tree and print the root node. 
Examples: 
 

Input : arr[] = { 5, 4, 8, 10, 6 }
Output : Value at Root Node = 2
Explanation : The image given above shows the 
segment tree corresponding to the given
set leaf nodes.

 

Prerequisites: Segment Trees 
In this Segment Tree, we carry two operations:- GCD and LCM.
Now, along with the information which is passed recursively for the sub-trees, information regarding the operation to be carried out at that level is also passed since these operations alternate levelwise. It is important to note that a parent node when calls its left and right children the same operation information is passed to both the children as they are on the same level.
Let’s represent the two operations i.e GCD and LCM by 0 and 1 respectively. Then, if at Level i GCD operation is performed then at Level (i + 1) LCM operation will be performed. Thus if Level i has 0 as operation then level (i + 1) will have 1 as operation. 
 

Operation at Level (i + 1) = ! (Operation at Level i)
where,
Operation at Level i ∊ {0, 1}

Careful analysis of the image suggests that if the height of the tree is even then the root node is a result of LCM operation of its left and right children else a result of GCD operation. 
 



CPP




#include <bits/stdc++.h>
using namespace std;
 
// Recursive function to return gcd of a and b
int gcd(int a, int b)
{
    // Everything divides 0
    if (a == 0 || b == 0)
       return 0;
  
    // base case
    if (a == b)
        return a;
  
    // a is greater
    if (a > b)
        return gcd(a-b, b);
    return gcd(a, b-a);
}
 
// A utility function to get the middle index from
// corner indexes.
int getMid(int s, int e) { return s + (e - s) / 2; }
 
void STconstructUtill(int arr[], int ss, int se, int* st,
                                          int si, int op)
{
    // If there is one element in array, store it in
    // current node of segment tree and return
    if (ss == se) {
        st[si] = arr[ss];
        return;
    }
 
    // If there are more than one elements, then recur
    // for left and right subtrees and store the sum of
    // values in this node
    int mid = getMid(ss, se);
 
    // Build the left and the right subtrees by using
    // the fact that operation at level (i + 1) = !
    // (operation at level i)
    STconstructUtill(arr, ss, mid, st, si * 2 + 1, !op);
    STconstructUtill(arr, mid + 1, se, st, si * 2 + 2, !op);
 
    // merge the left and right subtrees by checking
    // the operation to be carried. If operation = 1,
    // then do GCD else LCM
    if (op == 1) {
        // GCD operation
        st[si] = __gcd(st[2 * si + 1], st[2 * si + 2]);
    }
    else {
        // LCM operation
        st[si] = (st[2 * si + 1] * st[2 * si + 2]) /
                   (gcd(st[2 * si + 1], st[2 * si + 2]));
    }
}
 
/* Function to construct segment tree from given array.
This function allocates memory for segment tree and
calls STconstructUtil() to fill the allocated memory */
int* STconstruct(int arr[], int n)
{
    // Allocate memory for segment tree
 
    // Height of segment tree
    int x = (int)(ceil(log2(n)));
 
    // maximum size of segment tree
    int max_size = 2 * (int)pow(2, x) - 1;
 
    // allocate memory
    int* st = new int[max_size];
 
    // operation = 1(GCD) if Height of tree is
    // even else it is 0(LCM) for the root node
    int opAtRoot = (x % 2 == 0 ? 0 : 1);
 
    // Fill the allocated memory st
    STconstructUtill(arr, 0, n - 1, st, 0, opAtRoot);
 
    // Return the constructed segment tree
    return st;
}
 
int main()
{
    int arr[] = { 5, 4, 8, 10, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Build segment tree
    int* st = STconstruct(arr, n);
 
    // 0-based indexing in segment tree
    int rootIndex = 0;
 
    cout << "Value at Root Node = " << st[rootIndex];
 
    return 0;
}

Java




import java.io.*;
import java.util.*;
class GFG
{
 
  // Recursive function to return gcd of a and b
  static int gcd(int a, int b)
  {
 
    // Everything divides 0 
    if (a == 0 || b == 0)
      return 0;
 
    // base case
    if (a == b)
      return a;
 
    // a is greater
    if (a > b)
      return gcd(a - b, b);
    return gcd(a, b - a);
  }
 
  // A utility function to get the middle index from
  // corner indexes.
  static int getMid(int s, int e) { return s + (e - s) / 2; }
  static void STconstructUtill(int[] arr, int ss,
                               int se, int[] st, 
                               int si, boolean op)
  {
 
    // If there is one element in array, store it in
    // current node of segment tree and return
    if (ss == se)
    {
      st[si] = arr[ss];
      return;
    }
 
    // If there are more than one elements, then recur
    // for left and right subtrees and store the sum of
    // values in this node
    int mid = getMid(ss, se);
 
    // Build the left and the right subtrees by using
    // the fact that operation at level (i + 1) = !
    // (operation at level i)
    STconstructUtill(arr, ss, mid, st, si * 2 + 1, !op);
    STconstructUtill(arr, mid + 1, se, st, si * 2 + 2, !op);
 
    // merge the left and right subtrees by checking
    // the operation to be carried. If operation = 1,
    // then do GCD else LCM
    if(op == true)
    {
 
      // GCD operation
      st[si] = gcd(st[2 * si + 1], st[2 * si + 2]);
    }
    else
    {
 
      // LCM operation
      st[si] = (st[2 * si + 1] * st[2 * si + 2]) /
        (gcd(st[2 * si + 1], st[2 * si + 2]));
    }
  }
 
  /* Function to construct segment tree from given array.
    This function allocates memory for segment tree and 
    calls STconstructUtil() to fill the allocated memory */
  static int[] STconstruct(int arr[], int n)
  {
 
    // Allocate memory for segment tree
 
    // Height of segment tree
    int x = (int)(Math.ceil((Math.log(n)/Math.log(2))));
 
    // maximum size of segment tree
    int max_size = 2 * (int)Math.pow(2, x) - 1;
 
    // allocate memory
    int[] st = new int[max_size];
    boolean opAtRoot;
 
    // operation = 1(GCD) if Height of tree is
    // even else it is 0(LCM) for the root node
    if(x % 2 == 0)
    {
      opAtRoot = false;
    }
    else
    {
      opAtRoot = true;
    }
 
    // Fill the allocated memory st
    STconstructUtill(arr, 0, n - 1, st, 0, opAtRoot);
 
    // Return the constructed segment tree
    return st;
  }
 
  // Driver code
  public static void main (String[] args)
  {
    int[] arr = { 5, 4, 8, 10, 6 };
    int n = arr.length;
 
    // Build segment tree
    int[] st=STconstruct(arr, n);
 
    // 0-based indexing in segment tree
    System.out.println("Value at Root Node = " + st[0]);
  }
}
 
// This code is contributed by avanitrachhadiya2155

Python3




from math import ceil,floor,log
 
# Recursive function to return gcd of a and b
def gcd(a, b):
 
    # Everything divides 0
    if (a == 0 or b == 0):
        return 0
 
    # base case
    if (a == b):
        return a
 
    # a is greater
    if (a > b):
        return gcd(a - b, b)
    return gcd(a, b - a)
 
# A utility function to get the middle index from
# corner indexes.
def getMid(s, e):
    return s + (e - s) // 2
 
def STconstructUtill(arr, ss, se, st, si, op):
     
    # If there is one element in array, store it in
    # current node of segment tree and return
    if (ss == se):
        st[si] = arr[ss]
        return
 
    # If there are more than one elements, then recur
    # for left and right subtrees and store the sum of
    # values in this node
    mid = getMid(ss, se)
 
    # Build the left and the right subtrees by using
    # the fact that operation at level (i + 1) = !
    # (operation at level i)
    STconstructUtill(arr, ss, mid, st, si * 2 + 1, not op)
    STconstructUtill(arr, mid + 1, se, st, si * 2 + 2, not op)
 
    # merge the left and right subtrees by checking
    # the operation to be carried. If operation = 1,
    # then do GCD else LCM
    if (op == 1):
         
        # GCD operation
        st[si] =gcd(st[2 * si + 1], st[2 * si + 2])
    else :
         
        # LCM operation
        st[si] = (st[2 * si + 1] * st[2 * si + 2]) //(gcd(st[2 * si + 1], st[2 * si + 2]))
#
# /* Function to construct segment tree from given array.
# This function allocates memory for segment tree and
# calls STconstructUtil() to fill the allocated memory */
def STconstruct(arr, n):
    # Allocate memory for segment tree
 
    # Height of segment tree
    x = ceil(log(n, 2))
 
    # maximum size of segment tree
    max_size = 2 *pow(2, x) - 1
 
    # allocate memory
    st = [0]*max_size
 
    # operation = 1(GCD) if Height of tree is
    # even else it is 0(LCM) for the root node
    if (x % 2 == 0):
        opAtRoot = 0
    else:
        opAtRoot = 1
 
    # Fill the allocated memory st
    STconstructUtill(arr, 0, n - 1, st, 0, opAtRoot)
 
    # Return the constructed segment tree
    return st
 
# Driver code
if __name__ == '__main__':
    arr = [5, 4, 8, 10, 6]
    n = len(arr)
 
    # Build segment tree
    st = STconstruct(arr, n)
 
    # 0-based indexing in segment tree
    rootIndex = 0
 
    print("Value at Root Node = ",st[rootIndex])
     
# This code is contributed by mohit kumar 29

C#




using System;
 
class GFG
{
 
  // Recursive function to return gcd of a and b
  static int gcd(int a, int b)
  {
 
    // Everything divides 0 
    if (a == 0 || b == 0)
      return 0;
 
    // base case
    if (a == b)
      return a;
 
    // a is greater
    if (a > b)
      return gcd(a - b, b);
    return gcd(a, b - a);
  }
 
  // A utility function to get the middle index from
  // corner indexes.
  static int getMid(int s, int e) { return s + (e - s) / 2; }
  static void STconstructUtill(int[] arr, int ss,
                               int se, int[] st,
                               int si, bool op)
  {
 
    // If there is one element in array, store it in
    // current node of segment tree and return
    if (ss == se)
    {
      st[si] = arr[ss];
      return;
    }
 
    // If there are more than one elements, then recur
    // for left and right subtrees and store the sum of
    // values in this node
    int mid = getMid(ss, se);
 
    // Build the left and the right subtrees by using
    // the fact that operation at level (i + 1) = !
    // (operation at level i)
    STconstructUtill(arr, ss, mid, st, si * 2 + 1, !op);
    STconstructUtill(arr, mid + 1, se, st, si * 2 + 2, !op);
 
    // merge the left and right subtrees by checking
    // the operation to be carried. If operation = 1,
    // then do GCD else LCM
    if(op == true)
    {
 
      // GCD operation
      st[si] = gcd(st[2 * si + 1], st[2 * si + 2]);
    }
    else
    {
 
      // LCM operation
      st[si] = (st[2 * si + 1] * st[2 * si + 2]) /
        (gcd(st[2 * si + 1], st[2 * si + 2]));
    }
  }
 
  /* Function to construct segment tree from given array.
    This function allocates memory for segment tree and 
    calls STconstructUtil() to fill the allocated memory */
  static int[] STconstruct(int[] arr, int n)
  {
 
    // Allocate memory for segment tree
    // Height of segment tree
    int x = (int)(Math.Ceiling((Math.Log(n)/Math.Log(2))));
 
    // maximum size of segment tree
    int max_size = 2 * (int)Math.Pow(2, x) - 1;
 
    // allocate memory
    int[] st = new int[max_size];
    bool opAtRoot;
 
    // operation = 1(GCD) if Height of tree is
    // even else it is 0(LCM) for the root node
    if(x % 2 == 0)
    {
      opAtRoot = false;
    }
    else
    {
      opAtRoot = true;
    }
 
    // Fill the allocated memory st
    STconstructUtill(arr, 0, n - 1, st, 0, opAtRoot);
 
    // Return the constructed segment tree
    return st;
  }
 
  // Driver code
  static public void Main ()
  {
    int[] arr = { 5, 4, 8, 10, 6 };
    int n = arr.Length;
 
    // Build segment tree
    int[] st=STconstruct(arr, n);
 
    // 0-based indexing in segment tree
    Console.WriteLine("Value at Root Node = " + st[0]);
  }
}
 
//  This code is contributed by rag2127

Javascript




<script>
// Recursive function to return gcd of a and b
    function gcd(a , b) {
 
        // Everything divides 0
        if (a == 0 || b == 0)
            return 0;
 
        // base case
        if (a == b)
            return a;
 
        // a is greater
        if (a > b)
            return gcd(a - b, b);
        return gcd(a, b - a);
    }
 
    // A utility function to get the middle index from
    // corner indexes.
    function getMid(s , e) {
        return s + parseInt((e - s) / 2);
    }
 
    function STconstructUtill(arr , ss , se,  st , si, op) {
 
        // If there is one element in array, store it in
        // current node of segment tree and return
        if (ss == se) {
            st[si] = arr[ss];
            return;
        }
 
        // If there are more than one elements, then recur
        // for left and right subtrees and store the sum of
        // values in this node
        var mid = getMid(ss, se);
 
        // Build the left and the right subtrees by using
        // the fact that operation at level (i + 1) = !
        // (operation at level i)
        STconstructUtill(arr, ss, mid, st, si * 2 + 1, !op);
        STconstructUtill(arr, mid + 1, se, st, si * 2 + 2, !op);
 
        // merge the left and right subtrees by checking
        // the operation to be carried. If operation = 1,
        // then do GCD else LCM
        if (op == true) {
 
            // GCD operation
            st[si] = gcd(st[2 * si + 1], st[2 * si + 2]);
        } else {
 
            // LCM operation
            st[si] = (st[2 * si + 1] * st[2 * si + 2]) / (gcd(st[2 * si + 1], st[2 * si + 2]));
        }
    }
 
    /*
     * Function to construct segment tree from given array. This function allocates
     * memory for segment tree and calls STconstructUtil() to fill the allocated
     * memory
     */
    function STconstruct(arr , n) {
 
        // Allocate memory for segment tree
 
        // Height of segment tree
        var x = parseInt( (Math.ceil((Math.log(n) / Math.log(2)))));
 
        // maximum size of segment tree
        var max_size = 2 * parseInt( Math.pow(2, x) - 1);
 
        // allocate memory
        var st = Array(max_size).fill(0);
        var opAtRoot;
 
        // operation = 1(GCD) if Height of tree is
        // even else it is 0(LCM) for the root node
        if (x % 2 == 0) {
            opAtRoot = false;
        } else {
            opAtRoot = true;
        }
 
        // Fill the allocated memory st
        STconstructUtill(arr, 0, n - 1, st, 0, opAtRoot);
 
        // Return the constructed segment tree
        return st;
    }
 
    // Driver code
     
        var arr = [ 5, 4, 8, 10, 6 ];
        var n = arr.length;
 
        // Build segment tree
        var st = STconstruct(arr, n);
 
        // 0-based indexing in segment tree
        document.write("Value at Root Node = " + st[0]);
 
// This code is contributed by umadevi9616
</script>

Output: 
 

Value at Root Node = 2

Time complexity for tree construction is O(n), as there are total 2*n-1 nodes and value at every node us calculated at once.
Now to perform point updates i.e. update the value with given index and value, can be done by traversing down the tree to the leaf node and performing the update. 
While coming back to the root node we build the tree again similar to the build() function by passing the operation to be performed at every level and storing the result of applying that operation on values of its left and right children and storing the result into that node.
Consider the following Segment tree after performing the update, 
arr[2] = 7 
Now the updated segment tree looks like this:
 

 

Here nodes in black denote the fact that they are updated.
 

CPP




#include <bits/stdc++.h>
using namespace std;
 
// Recursive function to return gcd of a and b
int gcd(int a, int b)
{
    // Everything divides 0
    if (a == 0 || b == 0)
       return 0;
  
    // base case
    if (a == b)
        return a;
  
    // a is greater
    if (a > b)
        return gcd(a-b, b);
    return gcd(a, b-a);
}
 
// A utility function to get the middle index from
// corner indexes.
int getMid(int s, int e) { return s + (e - s) / 2; }
 
void STconstructUtill(int arr[], int ss, int se, int* st,
                                          int si, int op)
{
    // If there is one element in array, store it in
    // current node of segment tree and return
    if (ss == se) {
        st[si] = arr[ss];
        return;
    }
 
    // If there are more than one elements, then recur
    // for left and right subtrees and store the sum of
    // values in this node
    int mid = getMid(ss, se);
 
    // Build the left and the right subtrees by using
    // the fact that operation at level (i + 1) = !
    // (operation at level i)
    STconstructUtill(arr, ss, mid, st, si * 2 + 1, !op);
    STconstructUtill(arr, mid + 1, se, st, si * 2 + 2, !op);
 
    // merge the left and right subtrees by checking
    // the operation to be carried. If operation = 1,
    // then do GCD else LCM
    if (op == 1) {
        // GCD operation
        st[si] = gcd(st[2 * si + 1], st[2 * si + 2]);
    }
    else {
        // LCM operation
        st[si] = (st[2 * si + 1] * st[2 * si + 2]) /
                  (gcd(st[2 * si + 1], st[2 * si + 2]));
    }
}
 
void updateUtil(int* st, int ss, int se, int ind, int val,
                                            int si, int op)
{
    // Base Case: If the input index lies outside
    // this segment
    if (ind < ss || ind > se)
        return;
 
    // If the input index is in range of this node,
    // then update the value of the node and its
    // children
 
    // leaf node
    if (ss == se && ss == ind) {
        st[si] = val;
        return;
    }
 
    int mid = getMid(ss, se);
 
    // Update the left and the right subtrees by
    // using the fact that operation at level
    // (i + 1) = ! (operation at level i)
    updateUtil(st, ss, mid, ind, val, 2 * si + 1, !op);
    updateUtil(st, mid + 1, se, ind, val, 2 * si + 2, !op);
 
    // merge the left and right subtrees by checking
    // the operation to be carried. If operation = 1,
    // then do GCD else LCM
    if (op == 1) {
 
        // GCD operation
        st[si] = gcd(st[2 * si + 1], st[2 * si + 2]);
    }
    else {
 
        // LCM operation
        st[si] = (st[2 * si + 1] * st[2 * si + 2]) /
                  (gcd(st[2 * si + 1], st[2 * si + 2]));
    }
}
 
void update(int arr[], int* st, int n, int ind, int val)
{
    // Check for erroneous input index
    if (ind < 0 || ind > n - 1) {
        printf("Invalid Input");
        return;
    }
 
    // Height of segment tree
    int x = (int)(ceil(log2(n)));
 
    // operation = 1(GCD) if Height of tree is
    // even else it is 0(LCM) for the root node
    int opAtRoot = (x % 2 == 0 ? 0 : 1);
 
    arr[ind] = val;
 
    // Update the values of nodes in segment tree
    updateUtil(st, 0, n - 1, ind, val, 0, opAtRoot);
}
 
/* Function to construct segment tree from given array.
This function allocates memory for segment tree and
calls STconstructUtil() to fill the allocated memory */
int* STconstruct(int arr[], int n)
{
    // Allocate memory for segment tree
 
    // Height of segment tree
    int x = (int)(ceil(log2(n)));
 
    // maximum size of segment tree
    int max_size = 2 * (int)pow(2, x) - 1;
 
    // allocate memory
    int* st = new int[max_size];
 
    // operation = 1(GCD) if Height of tree is
    // even else it is 0(LCM) for the root node
    int opAtRoot = (x % 2 == 0 ? 0 : 1);
 
    // Fill the allocated memory st
    STconstructUtill(arr, 0, n - 1, st, 0, opAtRoot);
 
    // Return the constructed segment tree
    return st;
}
 
int main()
{
    int arr[] = { 5, 4, 8, 10, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Build segment tree
    int* st = STconstruct(arr, n);
 
    // 0-based indexing in segment tree
    int rootIndex = 0;
 
    cout << "Old Value at Root Node = " <<
                             st[rootIndex] << endl;
 
    // perform update arr[2] = 7
    update(arr, st, n, 2, 7);
 
    cout << "New Value at Root Node = " <<
                             st[rootIndex] << endl;
 
    return 0;
}

Java




import java.util.*;
public class GFG
{
  // Recursive function to return gcd of a and b
  static int gcd(int a, int b)
  {
 
    // Everything divides 0
    if (a == 0 || b == 0)
      return 0;
 
    // base case
    if (a == b)
      return a;
 
    // a is greater
    if (a > b)
      return gcd(a - b, b);
    return gcd(a, b - a);
  }
 
  // A utility function to get the middle index from
  // corner indexes.
  static int getMid(int s, int e)
  {
    return s + (e - s) / 2;
  }
 
  static void STconstructUtill(int[] arr, int ss, int se, int[] st,
                               int si, int op)
  {
    // If there is one element in array, store it in
    // current node of segment tree and return
    if (ss == se)
    {
      st[si] = arr[ss];
      return;
    }
 
    // If there are more than one elements, then recur
    // for left and right subtrees and store the sum of
    // values in this node
    int mid = getMid(ss, se);
 
    // Build the left and the right subtrees by using
    // the fact that operation at level (i + 1) = !
    // (operation at level i)
    if(op != 0)
    {
      STconstructUtill(arr, ss, mid, st,
                       si * 2 + 1, 0);
    }
    else{
      STconstructUtill(arr, ss, mid, st,
                       si * 2 + 1, 1);
    }
 
    if(op != 0)
    {
      STconstructUtill(arr, mid + 1, se, st,
                       si * 2 + 2, 0);
    }
    else{
      STconstructUtill(arr, mid + 1, se, st,
                       si * 2 + 2, 1);
    }
 
    // merge the left and right subtrees by checking
    // the operation to be carried. If operation = 1,
    // then do GCD else LCM
    if (op == 1)
    {
 
      // GCD operation
      st[si] = gcd(st[2 * si + 1],
                   st[2 * si + 2]);
    }
    else {
      // LCM operation
      st[si] = (st[2 * si + 1] * st[2 * si + 2]) /
        (gcd(st[2 * si + 1], st[2 * si + 2]));
    }
  }
 
  static void updateUtil(int[] st, int ss, int se,
                         int ind, int val,
                         int si, int op)
  {
 
    // Base Case: If the input index lies outside
    // this segment
    if (ind < ss || ind > se)
      return;
 
    // If the input index is in range of this node,
    // then update the value of the node and its
    // children
 
    // leaf node
    if (ss == se && ss == ind)
    {
      st[si] = val;
      return;
    }
    int mid = getMid(ss, se);
 
    // Update the left and the right subtrees by
    // using the fact that operation at level
    // (i + 1) = ! (operation at level i)
    if(op != 0)
    {
      updateUtil(st, ss, mid, ind,
                 val, 2 * si + 1, 0);
    }
    else{
      updateUtil(st, ss, mid, ind,
                 val, 2 * si + 1, 1);
    }
 
    if(op != 0)
    {
      updateUtil(st, mid + 1, se, ind,
                 val, 2 * si + 2, 0);
    }
    else{
      updateUtil(st, mid + 1, se, ind,
                 val, 2 * si + 2, 1);
    }
 
    // merge the left and right subtrees by checking
    // the operation to be carried. If operation = 1,
    // then do GCD else LCM
    if (op == 1) {
 
      // GCD operation
      st[si] = gcd(st[2 * si + 1], st[2 * si + 2]);
    }
    else {
 
      // LCM operation
      st[si] = (st[2 * si + 1] * st[2 * si + 2]) /
        (gcd(st[2 * si + 1], st[2 * si + 2]));
    }
  }
 
  static void update(int[] arr, int[] st,
                     int n, int ind, int val)
  {
    // Check for erroneous input index
    if (ind < 0 || ind > n - 1)
    {
      System.out.print("Invalid Input");
      return;
    }
 
    // Height of segment tree
    int x = (int)(Math.ceil(Math.log(n) / Math.log(2)));
 
    // operation = 1(GCD) if Height of tree is
    // even else it is 0(LCM) for the root node
    int opAtRoot = (x % 2 == 0 ? 0 : 1);
 
    arr[ind] = val;
 
    // Update the values of nodes in segment tree
    updateUtil(st, 0, n - 1, ind, val, 0, opAtRoot);
  }
 
  /* Function to construct segment tree from given array.
    This function allocates memory for segment tree and
    calls STconstructUtil() to fill the allocated memory */
  static int[] STconstruct(int[] arr, int n)
  {
    // Allocate memory for segment tree
 
    // Height of segment tree
    int x = (int)(Math.ceil(Math.log(n) / Math.log(2)));
 
    // maximum size of segment tree
    int max_size = 2 * (int)Math.pow(2, x) - 1;
 
    // allocate memory
    int[] st = new int[max_size];
 
    // operation = 1(GCD) if Height of tree is
    // even else it is 0(LCM) for the root node
    int opAtRoot = (x % 2 == 0 ? 0 : 1);
 
    // Fill the allocated memory st
    STconstructUtill(arr, 0, n - 1, st, 0, opAtRoot);
 
    // Return the constructed segment tree
    return st;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int[] arr = { 5, 4, 8, 10, 6 };
    int n = arr.length;
 
    // Build segment tree
    int[] st = STconstruct(arr, n);
 
    // 0-based indexing in segment tree
    int rootIndex = 0;
 
    System.out.println("Old Value at Root Node = " + st[rootIndex]);
 
    // perform update arr[2] = 7
    update(arr, st, n, 2, 7);
    System.out.println("New Value at Root Node = " + st[rootIndex]);
  }
}
 
// This code is contributed by divyeshrabadiya07.

C#




using System;
class GFG
{
     
    // Recursive function to return gcd of a and b
    static int gcd(int a, int b)
    {
       
        // Everything divides 0
        if (a == 0 || b == 0)
           return 0;
       
        // base case
        if (a == b)
            return a;
       
        // a is greater
        if (a > b)
            return gcd(a - b, b);
        return gcd(a, b - a);
    }
     
    // A utility function to get the middle index from
    // corner indexes.
    static int getMid(int s, int e)
    {
        return s + (e - s) / 2;
    }
      
    static void STconstructUtill(int[] arr, int ss, int se, int[] st,
                                              int si, int op)
    {
        // If there is one element in array, store it in
        // current node of segment tree and return
        if (ss == se)
        {
            st[si] = arr[ss];
            return;
        }
      
        // If there are more than one elements, then recur
        // for left and right subtrees and store the sum of
        // values in this node
        int mid = getMid(ss, se);
      
        // Build the left and the right subtrees by using
        // the fact that operation at level (i + 1) = !
        // (operation at level i)
        if(op != 0)
        {
            STconstructUtill(arr, ss, mid, st,
                             si * 2 + 1, 0);
        }
        else{
            STconstructUtill(arr, ss, mid, st,
                             si * 2 + 1, 1);
        }
         
        if(op != 0)
        {
            STconstructUtill(arr, mid + 1, se, st,
                             si * 2 + 2, 0);
        }
        else{
            STconstructUtill(arr, mid + 1, se, st,
                             si * 2 + 2, 1);
        }
      
        // merge the left and right subtrees by checking
        // the operation to be carried. If operation = 1,
        // then do GCD else LCM
        if (op == 1)
        {
           
            // GCD operation
            st[si] = gcd(st[2 * si + 1],
                         st[2 * si + 2]);
        }
        else {
            // LCM operation
            st[si] = (st[2 * si + 1] * st[2 * si + 2]) /
                      (gcd(st[2 * si + 1], st[2 * si + 2]));
        }
    }
      
    static void updateUtil(int[] st, int ss, int se,
                           int ind, int val,
                           int si, int op)
    {
       
        // Base Case: If the input index lies outside
        // this segment
        if (ind < ss || ind > se)
            return;
      
        // If the input index is in range of this node,
        // then update the value of the node and its
        // children
      
        // leaf node
        if (ss == se && ss == ind)
        {
            st[si] = val;
            return;
        }
        int mid = getMid(ss, se);
      
        // Update the left and the right subtrees by
        // using the fact that operation at level
        // (i + 1) = ! (operation at level i)
        if(op != 0)
        {
            updateUtil(st, ss, mid, ind,
                       val, 2 * si + 1, 0);
        }
        else{
            updateUtil(st, ss, mid, ind,
                       val, 2 * si + 1, 1);
        }
         
        if(op != 0)
        {
            updateUtil(st, mid + 1, se, ind,
                       val, 2 * si + 2, 0);
        }
        else{
            updateUtil(st, mid + 1, se, ind,
                       val, 2 * si + 2, 1);
        }
      
        // merge the left and right subtrees by checking
        // the operation to be carried. If operation = 1,
        // then do GCD else LCM
        if (op == 1) {
      
            // GCD operation
            st[si] = gcd(st[2 * si + 1], st[2 * si + 2]);
        }
        else {
      
            // LCM operation
            st[si] = (st[2 * si + 1] * st[2 * si + 2]) /
                      (gcd(st[2 * si + 1], st[2 * si + 2]));
        }
    }
      
    static void update(int[] arr, int[] st,
                       int n, int ind, int val)
    {
        // Check for erroneous input index
        if (ind < 0 || ind > n - 1)
        {
            Console.Write("Invalid Input");
            return;
        }
      
        // Height of segment tree
        int x = (int)(Math.Ceiling(Math.Log(n, 2)));
      
        // operation = 1(GCD) if Height of tree is
        // even else it is 0(LCM) for the root node
        int opAtRoot = (x % 2 == 0 ? 0 : 1);
      
        arr[ind] = val;
      
        // Update the values of nodes in segment tree
        updateUtil(st, 0, n - 1, ind, val, 0, opAtRoot);
    }
      
    /* Function to construct segment tree from given array.
    This function allocates memory for segment tree and
    calls STconstructUtil() to fill the allocated memory */
    static int[] STconstruct(int[] arr, int n)
    {
        // Allocate memory for segment tree
      
        // Height of segment tree
        int x = (int)(Math.Ceiling(Math.Log(n, 2)));
      
        // maximum size of segment tree
        int max_size = 2 * (int)Math.Pow(2, x) - 1;
      
        // allocate memory
        int[] st = new int[max_size];
      
        // operation = 1(GCD) if Height of tree is
        // even else it is 0(LCM) for the root node
        int opAtRoot = (x % 2 == 0 ? 0 : 1);
      
        // Fill the allocated memory st
        STconstructUtill(arr, 0, n - 1, st, 0, opAtRoot);
      
        // Return the constructed segment tree
        return st;
    }
 
  // Driver code
  static void Main()
  {
    int[] arr = { 5, 4, 8, 10, 6 };
    int n = arr.Length;
  
    // Build segment tree
    int[] st = STconstruct(arr, n);
  
    // 0-based indexing in segment tree
    int rootIndex = 0;
  
    Console.WriteLine("Old Value at Root Node = " + st[rootIndex]);
  
    // perform update arr[2] = 7
    update(arr, st, n, 2, 7);
    Console.WriteLine("New Value at Root Node = " + st[rootIndex]);
  }
}
 
// This code is contributed by divyesh072019.

Javascript




<script>
 
    // Recursive function to return gcd of a and b
    function gcd(a , b) {
 
        // Everything divides 0
        if (a == 0 || b == 0)
            return 0;
 
        // base case
        if (a == b)
            return a;
 
        // a is greater
        if (a > b)
            return gcd(a - b, b);
        return gcd(a, b - a);
    }
 
    // A utility function to get the middle index from
    // corner indexes.
    function getMid(s , e) {
        return s + parseInt((e - s) / 2);
    }
 
    function STconstructUtill(arr , ss , se,  st , si , op) {
        // If there is one element in array, store it in
        // current node of segment tree and return
        if (ss == se) {
            st[si] = arr[ss];
            return;
        }
 
        // If there are more than one elements, then recur
        // for left and right subtrees and store the sum of
        // values in this node
        var mid = getMid(ss, se);
 
        // Build the left and the right subtrees by using
        // the fact that operation at level (i + 1) = !
        // (operation at level i)
        if (op != 0) {
            STconstructUtill(arr, ss, mid, st, si * 2 + 1, 0);
        } else {
            STconstructUtill(arr, ss, mid, st, si * 2 + 1, 1);
        }
 
        if (op != 0) {
            STconstructUtill(arr, mid + 1, se, st, si * 2 + 2, 0);
        } else {
            STconstructUtill(arr, mid + 1, se, st, si * 2 + 2, 1);
        }
 
        // merge the left and right subtrees by checking
        // the operation to be carried. If operation = 1,
        // then do GCD else LCM
        if (op == 1) {
 
            // GCD operation
            st[si] = gcd(st[2 * si + 1], st[2 * si + 2]);
        } else {
            // LCM operation
            st[si] = (st[2 * si + 1] * st[2 * si + 2]) /
            (gcd(st[2 * si + 1], st[2 * si + 2]));
        }
    }
 
    function updateUtil(st , ss , se , ind , val , si , op) {
 
        // Base Case: If the input index lies outside
        // this segment
        if (ind < ss || ind > se)
            return;
 
        // If the input index is in range of this node,
        // then update the value of the node and its
        // children
 
        // leaf node
        if (ss == se && ss == ind) {
            st[si] = val;
            return;
        }
        var mid = getMid(ss, se);
 
        // Update the left and the right subtrees by
        // using the fact that operation at level
        // (i + 1) = ! (operation at level i)
        if (op != 0) {
            updateUtil(st, ss, mid, ind, val, 2 * si + 1, 0);
        } else {
            updateUtil(st, ss, mid, ind, val, 2 * si + 1, 1);
        }
 
        if (op != 0) {
            updateUtil(st, mid + 1, se, ind, val, 2 * si + 2, 0);
        } else {
            updateUtil(st, mid + 1, se, ind, val, 2 * si + 2, 1);
        }
 
        // merge the left and right subtrees by checking
        // the operation to be carried. If operation = 1,
        // then do GCD else LCM
        if (op == 1) {
 
            // GCD operation
            st[si] = gcd(st[2 * si + 1], st[2 * si + 2]);
        } else {
 
            // LCM operation
            st[si] = (st[2 * si + 1] * st[2 * si + 2]) /
            (gcd(st[2 * si + 1], st[2 * si + 2]));
        }
    }
 
    function update(arr,  st , n , ind , val) {
        // Check for erroneous input index
        if (ind < 0 || ind > n - 1) {
            document.write("Invalid Input");
            return;
        }
 
        // Height of segment tree
        var x = parseInt( (Math.ceil(Math.log(n) / Math.log(2))));
 
        // operation = 1(GCD) if Height of tree is
        // even else it is 0(LCM) for the root node
        var opAtRoot = (x % 2 == 0 ? 0 : 1);
 
        arr[ind] = val;
 
        // Update the values of nodes in segment tree
        updateUtil(st, 0, n - 1, ind, val, 0, opAtRoot);
    }
 
    /*
     Function to construct segment tree from given array.
     This function allocates memory for
     segment tree and calls STconstructUtil() to
     fill the allocated memory
     */
    function STconstruct(arr , n) {
        // Allocate memory for segment tree
 
        // Height of segment tree
        var x = parseInt( (Math.ceil(Math.log(n) / Math.log(2))));
 
        // maximum size of segment tree
        var max_size = 2 * parseInt( Math.pow(2, x) - 1);
 
        // allocate memory
        var st = Array(max_size).fill(0);
 
        // operation = 1(GCD) if Height of tree is
        // even else it is 0(LCM) for the root node
        var opAtRoot = (x % 2 == 0 ? 0 : 1);
 
        // Fill the allocated memory st
        STconstructUtill(arr, 0, n - 1, st, 0, opAtRoot);
 
        // Return the constructed segment tree
        return st;
    }
 
    // Driver code
     
        var arr = [ 5, 4, 8, 10, 6 ];
        var n = arr.length;
 
        // Build segment tree
        var st = STconstruct(arr, n);
 
        // 0-based indexing in segment tree
        var rootIndex = 0;
 
        document.write("Old Value at Root Node = " + st[rootIndex]);
 
        // perform update arr[2] = 7
        update(arr, st, n, 2, 7);
        document.write("<br/>New Value at Root Node = " + st[rootIndex]);
 
// This code contributed by Rajput-Ji
 
</script>

Output: 

Old Value at Root Node = 2
New Value at Root Node = 1

The time complexity of update is also O(Logn). To update a leaf value, one node is processed at every level and number of levels is O(Logn).
 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with industry experts, please refer Geeks Classes Live




My Personal Notes arrow_drop_up
Recommended Articles
Page :