A Levelwise OR/XOR alternating segment tree is a segment tree, such that at every level the operations OR and XOR alternate. In other words at Level 1 the left and right sub-trees combine together by the OR operation i.e Parent node = Left Child OR Right Child and on Level 2 the leftÂ
and right sub-trees combine together by the XOR operation i.e Parent node = Left Child XOR Right Child
Such a type of Segment tree has the following type of structure:Â
Â
The operations (OR) and (XOR) indicate which operation was carried out to merge the child node
Given 2N leaf nodes, the task is to build such a segment tree and print the root nodeÂ
Examples:Â Â
Input : Leaves = {1, 6, 3, 7, 5, 9, 10, 4}
Output : Value at Root Node = 3
Explanation : The image given above shows the
segment tree corresponding to the given
set leaf nodes.
This is an Extension to the Classical Segment Tree where we represent each node as an integer and the parent node is built by first building the left and the right subtrees and then combining the results of the left and the right children into the parent node. This merging of the left and right children into the parent node is done by consistent operations, For example, MIN()/MAX() in Range Minimum Queries, Sum, XOR, OR, AND, etc. By consistent operations, we mean that this operation is performed to merge any nodeâs left and right child into the parent node by carrying the operation say OP on their results, where OP is a consistent operation.
In this Segment tree, we carry two operations that are -: OR and XOR.
Now we build the Segment tree in a similar fashion as we do in the classical version, but now when we recursively pass the information for the sub-trees we will also pass information regarding the operation to be carried out at that level since these operations alternate levelwise. Itâs 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 OR and XOR by 0 and 1 respectively. Then if at Level i we have an OR operation at Level (i + 1) we will have an XOR operation. There 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}
The parent-child relationship for a segment tree node is shown in the below image:Â
Now, we need to look at the operation to be carried out at root node.Â
Â
If we carefully look at the image then it would be easy to figure out that if the height of the tree is even then the root node is a result of XOR operation of its left and right children else a result of OR operation.Â
C++
// C++ program to build levelwise OR/XOR alternating// Segment tree#include <bits/stdc++.h>Â
using namespace std;Â
// A utility function to get the middle index from // corner indexes.int getMid(int s, int e) { return s + (e - s) / 2; }Â
// A recursive function that constructs Segment Tree// for array[ss..se]. // si is index of current node in segment tree st// operation denotes which operation is carried out // at that level to merge the left and right child. // It's either 0 or 1.void constructSTUtil(int arr[], int ss, int se, int* st,                                   int si, int operation){    // 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)    constructSTUtil(arr, ss, mid, st, si * 2 + 1, !operation);    constructSTUtil(arr, mid + 1, se, st, si * 2 + 2, !operation);Â
    // merge the left and right subtrees by checking     // the operation to be carried. If operation = 1,    // then do OR else XOR    if (operation == 1) {Â
        // OR operation        st[si] = (st[2 * si + 1] | st[2 * si + 2]);    }    else {Â
        // XOR operation        st[si] = (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 constructSTUtil() to fill the allocated memory */int* constructST(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(XOR) if Height of tree is    // even else it is 0(OR) for the root node    int operationAtRoot = (x % 2 == 0 ? 0 : 1);Â
    // Fill the allocated memory st    constructSTUtil(arr, 0, n - 1, st, 0, operationAtRoot);Â
    // Return the constructed segment tree    return st;}Â
// Driver Codeint main(){Â
    // leaf nodes    int leaves[] = { 1, 6, 3, 7, 5, 9, 10, 4 };Â
    int n = sizeof(leaves) / sizeof(leaves[0]);Â
    // Build the segment tree    int* segmentTree = constructST(leaves, n);Â
    // Root node is at index 0 considering    // 0-based indexing in segment Tree    int rootIndex = 0;Â
    // print value at rootIndex    cout << "Value at Root Node = " << segmentTree[rootIndex];} |
Java
// Java program to build levelwise OR/XOR alternating// Segment treeclass GFG{Â
// A utility function to get the middle index from// corner indexes.static int getMid(int s, int e){Â Â Â Â return s + (e - s) / 2;}Â
// A recursive function that constructs Segment Tree// for array[ss..se].// si is index of current node in segment tree st// operation denotes which operation is carried out// at that level to merge the left and right child.// It's either 0 or 1.static void constructSTUtil(int arr[], int ss, int se,                            int st[], int si,                             boolean operation) {         // 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)    constructSTUtil(arr, ss, mid, st,                     si * 2 + 1, !operation);    constructSTUtil(arr, mid + 1, se, st,                     si * 2 + 2, !operation);Â
    // Merge the left and right subtrees by checking    // the operation to be carried. If operation = 1,    // then do OR else XOR    if (operation)     {                 // OR operation        st[si] = (st[2 * si + 1] | st[2 * si + 2]);    }     else    {                 // XOR operation        st[si] = (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 // constructSTUtil() to fill the allocated memorystatic int[] constructST(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(XOR) if Height of tree is    // even else it is 0(OR) for the root node    boolean operationAtRoot = !(x % 2 == 0);Â
    // Fill the allocated memory st    constructSTUtil(arr, 0, n - 1, st,                     0, operationAtRoot);Â
    // Return the constructed segment tree    return st;}Â
// Driver Codepublic static void main(String[] args){         // Leaf nodes    int leaves[] = { 1, 6, 3, 7,                      5, 9, 10, 4 };Â
    int n = leaves.length;Â
    // Build the segment tree    int[] segmentTree = constructST(leaves, n);Â
    // Root node is at index 0 considering    // 0-based indexing in segment Tree    int rootIndex = 0;Â
    // Print value at rootIndex    System.out.println("Value at Root Node = " +                        segmentTree[rootIndex]);}}Â
// This code is contributed by sanjeev2552 |
Python3
# Python3 program to build levelwise # OR/XOR alternating Segment treeimport mathÂ
# A utility function to get the#Â middle index from corner indexes.def getMid(s, e):Â Â Â Â return s + (e - s) // 2Â
# A recursive function that constructs# Segment Tree for array[ss..se]. # 'si' is index of current node in segment # tree 'st', operation denotes which operation # is carried out at that level to merge the # left and right child. It's either 0 or 1.def constructSTUtil(arr, ss, se, st, si, operation):Â
    # 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)    constructSTUtil(arr, ss, mid, st,                     si * 2 + 1, not operation)    constructSTUtil(arr, mid + 1, se, st,                     si * 2 + 2, not operation)Â
    # merge the left and right subtrees     # by checking the operation to be     # carried. If operation = 1, then     # do OR else XOR    if (operation == 1) :Â
        # OR operation        st[si] = (st[2 * si + 1] |                   st[2 * si + 2])         else :Â
        # XOR operation        st[si] = (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 constructSTUtil() to fill the allocated memory '''def constructST(arr, n):Â
    # Allocate memory for segment treeÂ
    # Height of segment tree    x = int(math.ceil(math.log2(n)))Â
    # Maximum size of segment tree    max_size = 2 * int(pow(2, x)) - 1Â
    # Allocate memory    st = [0] * max_sizeÂ
    # operation = 1(XOR) if Height of tree is    # even else it is 0(OR) for the root node    operationAtRoot = (0 if x % 2 == 0 else 1)Â
    # Fill the allocated memory st    constructSTUtil(arr, 0, n - 1,                     st, 0, operationAtRoot)Â
    # Return the constructed segment tree    return stÂ
# Driver Codeif __name__ == "__main__":Â
    # leaf nodes    leaves = [ 1, 6, 3, 7, 5, 9, 10, 4 ]Â
    n = len(leaves)Â
    # Build the segment tree    segmentTree = constructST(leaves, n)Â
    # Root node is at index 0 considering    # 0-based indexing in segment Tree    rootIndex = 0Â
    # print value at rootIndex    print("Value at Root Node = " ,            segmentTree[rootIndex])Â
# This code is contributed by ChitraNayal |
C#
// C# program to build levelwise OR/XOR// alternating Segment treeusing System;Â
class GFG{     // A utility function to get the middle// index from corner indexes.static int getMid(int s, int e){    return s + (e - s) / 2;}  // A recursive function that constructs Segment Tree// for array[ss..se].// si is index of current node in segment tree st// operation denotes which operation is carried out// at that level to merge the left and right child.// It's either 0 or 1.static void constructSTUtil(int[] arr, int ss, int se,                            int[] st, int si,                             bool operation) {         // 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)    constructSTUtil(arr, ss, mid, st,                     si * 2 + 1, !operation);    constructSTUtil(arr, mid + 1, se, st,                     si * 2 + 2, !operation);      // Merge the left and right subtrees by checking    // the operation to be carried. If operation = 1,    // then do OR else XOR    if (operation)     {                 // OR operation        st[si] = (st[2 * si + 1] | st[2 * si + 2]);    }     else    {                 // XOR operation        st[si] = (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 // constructSTUtil() to fill the allocated memorystatic int[] constructST(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];      // Operation = 1(XOR) if Height of tree is    // even else it is 0(OR) for the root node    bool operationAtRoot = !(x % 2 == 0);      // Fill the allocated memory st    constructSTUtil(arr, 0, n - 1, st,                     0, operationAtRoot);      // Return the constructed segment tree    return st;}  // Driver Codestatic public void Main(){         // Leaf nodes    int[] leaves = { 1, 6, 3, 7,                      5, 9, 10, 4 };      int n = leaves.Length;      // Build the segment tree    int[] segmentTree = constructST(leaves, n);      // Root node is at index 0 considering    // 0-based indexing in segment Tree    int rootIndex = 0;      // Print value at rootIndex    Console.WriteLine("Value at Root Node = " +                       segmentTree[rootIndex]);}}Â
// This code is contributed by rag2127 |
Javascript
<script>// Javascript program to build levelwise OR/XOR// alternating Segment treeÂ
Â
Â
// A utility function to get the middle// index from corner indexes.function getMid(s, e) {Â Â Â Â return s + Math.floor((e - s) / 2);}Â
// A recursive function that constructs Segment Tree// for array[ss..se].// si is index of current node in segment tree st// operation denotes which operation is carried out// at that level to merge the left and right child.// It's either 0 or 1.function constructSTUtil(arr, ss, se, st, si, operation) {Â
    // 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    let 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)    constructSTUtil(arr, ss, mid, st, si * 2 + 1, !operation);    constructSTUtil(arr, mid + 1, se, st, si * 2 + 2, !operation);Â
    // Merge the left and right subtrees by checking    // the operation to be carried. If operation = 1,    // then do OR else XOR    if (operation) {Â
        // OR operation        st[si] = (st[2 * si + 1] | st[2 * si + 2]);    }    else {Â
        // XOR operation        st[si] = (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// constructSTUtil() to fill the allocated memoryfunction constructST(arr, n) {Â
    // Allocate memory for segment treeÂ
    // Height of segment tree    let x = Math.ceil(Math.log(n) / Math.log(2));Â
    // Maximum size of segment tree    let max_size = 2 * Math.pow(2, x) - 1;Â
    // Allocate memory    let st = new Array(max_size);Â
    // Operation = 1(XOR) if Height of tree is    // even else it is 0(OR) for the root node    let operationAtRoot = !(x % 2 == 0);Â
    // Fill the allocated memory st    constructSTUtil(arr, 0, n - 1, st,        0, operationAtRoot);Â
    // Return the constructed segment tree    return st;}Â
// Driver CodeÂ
// Leaf nodeslet leaves = [1, 6, 3, 7, 5, 9, 10, 4];Â
let n = leaves.length;Â
// Build the segment treelet segmentTree = constructST(leaves, n);Â
// Root node is at index 0 considering// 0-based indexing in segment Treelet rootIndex = 0;Â
// Print value at rootIndexdocument.write("Value at Root Node = " + segmentTree[rootIndex]);Â
Â
// This code is contributed by gfgking</script> |
Value at Root Node = 3
Â
Time Complexity for tree construction is O(n). There are total 2n-1 nodes, and value of every node is calculated only once in tree construction.
We can also perform Point Updates in a similar manner. If we get an update to update the leaf at index i of the array leaves then we traverse down the tree to the leaf node and perform 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,Â
Leaves[0] = 13Â
Now the updated segment tree looks like this:
Â
Here the nodes in black denote the fact that they were updated
C++
// C++ program to build levelwise OR/XOR alternating // Segment tree (with updates)#include <bits/stdc++.h>Â
using namespace std;Â
// A utility function to get the middle index from// corner indexes.int getMid(int s, int e) { return s + (e - s) / 2; }Â
// A recursive function that constructs Segment Tree // for array[ss..se].// si is index of current node in segment tree st// operation denotes which operation is carried out// at that level to merge the left and right child. // Its either 0 or 1.void constructSTUtil(int arr[], int ss, int se, int* st,                                  int si, int operation){    // 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)    constructSTUtil(arr, ss, mid, st, si * 2 + 1, !operation);    constructSTUtil(arr, mid + 1, se, st, si * 2 + 2, !operation);Â
    // merge the left and right subtrees by checking    // the operation to be carried. If operation = 1,     // then do OR else XOR    if (operation == 1) {Â
        // OR operation        st[si] = (st[2 * si + 1] | st[2 * si + 2]);    }    else {        // XOR operation        st[si] = (st[2 * si + 1] ^ st[2 * si + 2]);    }}Â
/* A recursive function to update the nodes which have the given    index in their range. The following are parameters    st, si, ss and se are same as getSumUtil()    i   --> index of the element to be updated. This index is              in input array.   val --> Value to be assigned to arr[i] */void updateValueUtil(int* st, int ss, int se, int i,                     int val, int si, int operation){    // Base Case: If the input index lies outside     // this segment    if (i < ss || i > 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 == i) {        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)    updateValueUtil(st, ss, mid, i, val, 2 * si + 1, !operation);    updateValueUtil(st, mid + 1, se, i, val, 2 * si + 2, !operation);Â
    // merge the left and right subtrees by checking    // the operation to be carried. If operation = 1,     // then do OR else XOR    if (operation == 1) {                // OR operation        st[si] = (st[2 * si + 1] | st[2 * si + 2]);    }    else {Â
        // XOR operation        st[si] = (st[2 * si + 1] ^ st[2 * si + 2]);    }}Â
// The function to update a value in input array and // segment tree. It uses updateValueUtil() to update the // value in segment treevoid updateValue(int arr[], int* st, int n, int i, int new_val){    // Check for erroneous input index    if (i < 0 || i > n - 1) {        printf("Invalid Input");        return;    }Â
    // Height of segment tree    int x = (int)(ceil(log2(n)));Â
    // operation = 1(XOR) if Height of tree is    // even else it is 0(OR) for the root node    int operationAtRoot = (x % 2 == 0 ? 0 : 1);Â
    arr[i] = new_val;Â
    // Update the values of nodes in segment tree    updateValueUtil(st, 0, n - 1, i, new_val, 0, operationAtRoot);}Â
/* Function to construct segment tree from given array.   This function allocates memory for segment tree and    calls constructSTUtil() to fill the allocated memory */int* constructST(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(XOR) if Height of tree is     // even else it is 0(OR) for the root node    int operationAtRoot = (x % 2 == 0 ? 0 : 1);Â
    // Fill the allocated memory st    constructSTUtil(arr, 0, n - 1, st, 0, operationAtRoot);Â
    // Return the constructed segment tree    return st;}Â
// Driver Codeint main(){Â Â Â Â int leaves[] = { 1, 6, 3, 7, 5, 9, 10, 4 };Â Â Â Â int n = sizeof(leaves) / sizeof(leaves[0]);Â
    // Build the segment tree    int* segmentTree = constructST(leaves, n);Â
    // Root node is at index 0 considering    // 0-based indexing in segment Tree    int rootIndex = 0;Â
    // print old value at rootIndex    cout << "Old Value at Root Node = "         << segmentTree[rootIndex] << endl;Â
    // perform update leaves[0] = 13    updateValue(leaves, segmentTree, n, 0, 13);Â
    cout << "New Value at Root Node = "         << segmentTree[rootIndex];    return 0;} |
Java
// Java program to build levelwise OR/XOR alternating// Segment tree (with updates)Â
import java.io.*;Â
class GFG {Â Â Â Â public static int log2(int N)Â Â Â Â {Â
        // calculate log2 N indirectly        // using log() method        int result = (int)(Math.log(N) / Math.log(2));Â
        return result;    }    // A utility function to get the middle index from    // corner indexes.    public static int getMid(int s, int e)    {        return s + (e - s) / 2;    }Â
    // A recursive function that constructs Segment Tree    // for array[ss..se].    // si is index of current node in segment tree st    // operation denotes which operation is carried out    // at that level to merge the left and right child.    // Its either 0 or 1.    public static void constructSTUtil(int arr[], int ss,                                       int se, int st[],                                       int si,                                       int operation)    {        // 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)        constructSTUtil(arr, ss, mid, st, si * 2 + 1,                        operation ^ 1);        constructSTUtil(arr, mid + 1, se, st, si * 2 + 2,                        operation ^ 1);Â
        // merge the left and right subtrees by checking        // the operation to be carried. If operation = 1,        // then do OR else XOR        if (operation == 1) {Â
            // OR operation            st[si] = (st[2 * si + 1] | st[2 * si + 2]);        }        else {            // XOR operation            st[si] = (st[2 * si + 1] ^ st[2 * si + 2]);        }    }Â
    /* A recursive function to update the nodes which have       the given index in their range. The following are       parameters st, si, ss and se are same as getSumUtil()        i   --> index of the element to be updated. This       index is in input array.       val --> Value to be assigned to arr[i] */    public static void updateValueUtil(int st[], int ss,                                       int se, int i,                                       int val, int si,                                       int operation)    {        // Base Case: If the input index lies outside        // this segment        if (i < ss || i > 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 == i) {            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)        updateValueUtil(st, ss, mid, i, val, 2 * si + 1,                        operation ^ 1);        updateValueUtil(st, mid + 1, se, i, val, 2 * si + 2,                        operation ^ 1);Â
        // merge the left and right subtrees by checking        // the operation to be carried. If operation = 1,        // then do OR else XOR        if (operation == 1) {Â
            // OR operation            st[si] = (st[2 * si + 1] | st[2 * si + 2]);        }        else {Â
            // XOR operation            st[si] = (st[2 * si + 1] ^ st[2 * si + 2]);        }    }Â
    // The function to update a value in input array and    // segment tree. It uses updateValueUtil() to update the    // value in segment tree    public static void updateValue(int arr[], int st[],                                   int n, int i,                                   int new_val)    {        // Check for erroneous input index        if (i < 0 || i > n - 1) {            System.out.print("Invalid Input");            return;        }Â
        // Height of segment tree        int x = (int)(Math.ceil(log2(n)));Â
        // operation = 1(XOR) if Height of tree is        // even else it is 0(OR) for the root node        int operationAtRoot = (x % 2 == 0 ? 0 : 1);Â
        arr[i] = new_val;Â
        // Update the values of nodes in segment tree        updateValueUtil(st, 0, n - 1, i, new_val, 0,                        operationAtRoot);    }Â
    /* Function to construct segment tree from given array.       This function allocates memory for segment tree and       calls constructSTUtil() to fill the allocated memory     */    public static int[] constructST(int arr[], int n)    {        // Allocate memory for segment treeÂ
        // Height of segment tree        int x = (int)(Math.ceil(log2(n)));Â
        // 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(XOR) if Height of tree is        // even else it is 0(OR) for the root node        int operationAtRoot = (x % 2 == 0 ? 0 : 1);Â
        // Fill the allocated memory st        constructSTUtil(arr, 0, n - 1, st, 0,                        operationAtRoot);Â
        // Return the constructed segment tree        return st;    }Â
    // Driver code    public static void main(String[] args)    {        int leaves[] = { 1, 6, 3, 7, 5, 9, 10, 4 };        int n = leaves.length;Â
        // Build the segment tree        int segmentTree[] = constructST(leaves, n);Â
        // Root node is at index 0 considering        // 0-based indexing in segment Tree        int rootIndex = 0;Â
        // print old value at rootIndex        System.out.println("Old Value at Root Node = "                           + segmentTree[rootIndex]);Â
        // perform update leaves[0] = 13        updateValue(leaves, segmentTree, n, 0, 13);Â
        System.out.print("New Value at Root Node = "                         + segmentTree[rootIndex]);    }}Â
// This code is contributed by Rohit Pradhan |
Python3
# Python program to build levelwise OR/XOR alternating# Segment tree (with updates)Â
import mathÂ
Â
def getMid(s, e):Â Â Â Â return s + (e - s) // 2Â
Â
def constructSTUtil(arr, ss, se, st, si, level):    # 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)Â
    # Determine the operation to use for merging the left    # and right subtrees based on the current level    if (level % 2) == 0:        operation = 0 # OR operation    else:        operation = 1 # XOR operationÂ
    constructSTUtil(arr, ss, mid, st, si * 2 + 1, level+1)    constructSTUtil(arr, mid + 1, se, st, si * 2 + 2, level+1)Â
    # merge the left and right subtrees by checking    # the operation to be carried. If operation = 1,    # then do XOR else OR    if operation == 1:        # XOR operation        st[si] = st[2 * si + 1] ^ st[2 * si + 2]    else:        # OR operation        st[si] = st[2 * si + 1] | st[2 * si + 2]Â
Â
def updateValueUtil(st, ss, se, i, val, si, operation):    # Base Case: If the input index lies outside    # this segment    if i < ss or i > 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 and ss == i:        st[si] = val        returnÂ
    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)    updateValueUtil(st, ss, mid, i, val, 2 * si + 1, not operation)    updateValueUtil(st, mid + 1, se, i, val, 2 * si + 2, not operation)Â
    # merge the left and right subtrees by checking    # the operation to be carried. If operation = 1,    # then do OR else XOR    if operation == 1:        # OR operation        st[si] = st[2 * si + 1] | st[2 * si + 2]    else:        # XOR operation        st[si] = st[2 * si + 1] ^ st[2 * si + 2]Â
Â
def updateValue(arr, st, n, i, new_val):    # Check for erroneous input index    if i < 0 or i > n - 1:        print("Invalid Input")        returnÂ
    # Get the height of the tree after update    x = int(math.ceil(math.log2(n)))Â
    # Determine the operation to use for merging the left    # and right subtrees based on the height of the tree    if (x % 2) == 0:        operation = 0 # OR operation    else:        operation = 1 # XOR operationÂ
    arr[i] = new_valÂ
    # Update the values of nodes in segment tree    updateValueUtil(st, 0, n - 1, i, new_val, 0, operation)Â
    # Update the root node operation    if operation == 1:        # XOR operation        st[0] = st[1] ^ st[2]    else:        # OR operation        st[0] = st[1] | st[2]Â
Â
def constructST(arr, n):    # Height of segment tree    x = int(math.ceil(math.log2(n)))Â
    # Maximum size of segment tree    max_size = 2 * (2 ** x) - 1Â
    # Allocate memory for segment tree    st = [0] * max_sizeÂ
    # operation = 1(XOR) if Height of tree is    # even else it is 0(OR) for the root node    operationAtRoot = 1 if x % 2 == 0 else 0Â
    # Fill the allocated memory st    constructSTUtil(arr, 0, n - 1, st, 0, operationAtRoot)Â
    # Return the constructed segment tree    return stÂ
Â
# Driver Codeif __name__ == "__main__":Â Â Â Â leaves = [1, 6, 3, 7, 5, 9, 10, 4]Â Â Â Â n = len(leaves)Â
    # Build the segment tree    segmentTree = constructST(leaves, n)Â
    # Root node is at index 0 considering    # 0-based indexing in segment Tree    rootIndex = 0Â
    # print old value at rootIndex    print("Old Value at Root Node = ", segmentTree[rootIndex])Â
    # perform update leaves[0] = 13    updateValue(leaves, segmentTree, n, 0, 13)Â
    print("New Value at Root Node = ", segmentTree[rootIndex]) |
C#
// C# program to build levelwise OR/XOR alternating// Segment tree (with updates)using System;Â
class SegmentTree {    // A utility function to get the middle index from    // corner indexes.    static int GetMid(int s, int e)    {        return s + (e - s) / 2;    }    // A recursive function that constructs Segment Tree    // for array[ss..se].    // si is index of current node in segment tree st    // operation denotes which operation is carried out    // at that level to merge the left and right child.    // Its either 0 or 1.    static void ConstructSTUtil(int[] arr, int ss, int se,                                int[] st, int si,                                int operation)    {        // 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)        ConstructSTUtil(arr, ss, mid, st, si * 2 + 1,                        (operation == 1) ? 0 : 1);        ConstructSTUtil(arr, mid + 1, se, st, si * 2 + 2,                        (operation == 1) ? 0 : 1);        // merge the left and right subtrees by checking        // the operation to be carried. If operation = 1,        // then do OR else XOR        if (operation == 1) // Or Operation            st[si] = (st[2 * si + 1] | st[2 * si + 2]);        else // XOR operation            st[si] = (st[2 * si + 1] ^ st[2 * si + 2]);    }Â
    /* A recursive function to update the nodes which have       the given index in their range. The following are       parameters st, si, ss and se are same as getSumUtil()        i   --> index of the element to be updated. This       index is in input array.       val --> Value to be assigned to arr[i] */    static void UpdateValueUtil(int[] st, int ss, int se,                                int i, int val, int si,                                int operation)    {        // Base Case: If the input index lies outside        // this segment        if (i < ss || i > 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 == i) {            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)        UpdateValueUtil(st, ss, mid, i, val, 2 * si + 1,                        (operation == 1) ? 0 : 1);        UpdateValueUtil(st, mid + 1, se, i, val, 2 * si + 2,                        (operation == 1) ? 0 : 1);        // merge the left and right subtrees by checking        // the operation to be carried. If operation = 1,        // then do OR else XOR        if (operation == 1) // or            st[si] = (st[2 * si + 1] | st[2 * si + 2]);        else // xor            st[si] = (st[2 * si + 1] ^ st[2 * si + 2]);    }    // The function to update a value in input array and    // segment tree. It uses updateValueUtil() to update the    // value in segment treeÂ
    static void UpdateValue(int[] arr, int[] st, int n,                            int i, int new_val)    {        // check for erroenous input index        if (i < 0 || i > n - 1) {            Console.WriteLine("Invalid Input");            return;        }        // Height of segment tree        int x = (int)(Math.Ceiling(Math.Log(n)                                   / Math.Log(2)));        // operation = 1(XOR) if Height of tree is        // even else it is 0(OR) for the root node        int operationAtRoot = (x % 2 == 0 ? 0 : 1);Â
        arr[i] = new_val;        // Update the values of nodes in segment tree        UpdateValueUtil(st, 0, n - 1, i, new_val, 0,                        operationAtRoot);    }    /* Function to construct segment tree from given array.       This function allocates memory for segment tree and       calls constructSTUtil() to fill the allocated memory     */    static int[] ConstructST(int[] arr, int n)    {        // Allocate memory for segment treeÂ
        // Height of segment tree        int x = (int)(Math.Ceiling(Math.Log(n)                                   / Math.Log(2)));        int max_size = 2 * (int)Math.Pow(2, x) - 1;        int[] st = new int[max_size];        // operation = 1(XOR) if Height of tree is        // even else it is 0(OR) for the root node        int operationAtRoot = (x % 2 == 0 ? 0 : 1);Â
        ConstructSTUtil(arr, 0, n - 1, st, 0,                        operationAtRoot);Â
        return st;    }Â
    static void Main()    {        int[] leaves = { 1, 6, 3, 7, 5, 9, 10, 4 };        int n = leaves.Length;Â
        // Build the segment tree        int[] segmentTree = ConstructST(leaves, n);Â
        // Root node is at index 0 considering        // 0-based indexing in segment Tree        int rootIndex = 0;        Console.Write("Old Value at Root Node = ");        Console.Write(segmentTree[rootIndex]);        // perform update leaves[0] = 13        UpdateValue(leaves, segmentTree, n, 0, 13);Â
        Console.Write("New Value at Root Node = ");        Console.Write(segmentTree[rootIndex]);    }} |
Javascript
// Javascript program to build levelwise OR/XOR alternating// Segment tree (with updates)function getMid(s, e) {Â Â Â Â return s + Math.floor((e - s) / 2);}Â
function constructSTUtil(arr, ss, se, st, si, operation) {Â Â Â Â if (ss == se) {Â Â Â Â Â Â Â Â st[si] = arr[ss];Â Â Â Â Â Â Â Â return;Â Â Â Â }Â Â Â Â let mid = getMid(ss, se);Â Â Â Â constructSTUtil(arr, ss, mid, st, si * 2 + 1, operation == 1 ? 0 : 1);Â Â Â Â constructSTUtil(arr, mid + 1, se, st, si * 2 + 2, operation == 1 ? 0 : 1);Â Â Â Â if (operation == 1) {Â Â Â Â Â Â Â Â st[si] = (st[2 * si + 1] | st[2 * si + 2]);Â Â Â Â } else {Â Â Â Â Â Â Â Â st[si] = (st[2 * si + 1] ^ st[2 * si + 2]);Â Â Â Â }}Â
function updateValueUtil(st, ss, se, i, val, si, operation) {Â Â Â Â if (i < ss || i > se) {Â Â Â Â Â Â Â Â return;Â Â Â Â }Â Â Â Â if (ss == se && ss == i) {Â Â Â Â Â Â Â Â st[si] = val;Â Â Â Â Â Â Â Â return;Â Â Â Â }Â Â Â Â let mid = getMid(ss, se);Â Â Â Â updateValueUtil(st, ss, mid, i, val, 2 * si + 1, operation == 1 ? 0 : 1);Â Â Â Â updateValueUtil(st, mid + 1, se, i, val, 2 * si + 2, operation == 1 ? 0 : 1);Â Â Â Â if (operation == 1) {Â Â Â Â Â Â Â Â st[si] = (st[2 * si + 1] | st[2 * si + 2]);Â Â Â Â } else {Â Â Â Â Â Â Â Â st[si] = (st[2 * si + 1] ^ st[2 * si + 2]);Â Â Â Â }}Â
function updateValue(arr, st, n, i, new_val) {Â Â Â Â if (i < 0 || i > n - 1) {Â Â Â Â Â Â Â Â console.log("Invalid Input");Â Â Â Â Â Â Â Â return;Â Â Â Â }Â Â Â Â let x = Math.ceil(Math.log2(n));Â Â Â Â let operationAtRoot = x % 2 == 0 ? 0 : 1;Â Â Â Â arr[i] = new_val;Â Â Â Â updateValueUtil(st, 0, n - 1, i, new_val, 0, operationAtRoot);}Â
function constructST(arr, n) {Â Â Â Â let x = Math.ceil(Math.log2(n));Â Â Â Â let st_size = 2 * Math.pow(2, x) - 1;Â Â Â Â let st = new Array(st_size).fill(0);Â Â Â Â let operationAtRoot = x % 2 == 0 ? 0 : 1;Â Â Â Â constructSTUtil(arr, 0, n - 1, st, 0, operationAtRoot);Â Â Â Â return st;}Â
const leaves = [1, 6, 3, 7, 5, 9, 10, 4];const n = leaves.length;Â
// Build the segment treeconst segmentTree = constructST(leaves, n);Â
// Root node is at index 0 considering// 0-based indexing in segment Treeconst rootIndex = 0;console.log(`Old Value at Root Node = ${segmentTree[rootIndex]}`);// perform update leaves[0] = 13updateValue(leaves, segmentTree, n, 0, 13);Â
console.log(`New Value at Root Node = ${segmentTree[rootIndex]}`);Â
// The code is contributed by Nidhi goel. |
Old Value at Root Node = 3 New Value at Root Node = 11
Â
The time complexity of update is also O(Logn). To update a leaf value, we process one node at every level and number of levels is O(Logn).
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

