Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
Count total set bits in an array
Next article icon

Count and Toggle Queries on a Binary Array

Last Updated : 27 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a size n in which initially all elements are 0. The task is to perform multiple queries of following two types. The queries can appear in any order. 
 

1. toggle(start, end) : Toggle (0 into 1 or 1 into 0) the values from range ‘start’ to ‘end’.

2. count(start, end) : Count the number of 1’s within given range from ‘start’ to ‘end’.

Input : n = 5       // we have n = 5 blocks         toggle 1 2  // change 1 into 0 or 0 into 1         Toggle 2 4         Count  2 3  // count all 1's within the range         Toggle 2 4         Count  1 4  // count all 1's within the range Output : Total number of 1's in range 2 to 3 is = 1          Total number of 1's in range 1 to 4 is = 2

 

A simple solutionfor this problem is to traverse the complete range for “Toggle” query and when you get “Count” query then count all the 1’s for given range. But the time complexity for this approach will be O(q*n) where q=total number of queries.
An efficient solution for this problem is to use Segment Tree with Lazy Propagation. Here we collect the updates until we get a query for “Count”. When we get the query for “Count”, we make all the previously collected Toggle updates in array and then count number of 1’s with in the given range. 
Below is the implementation of above approach:
 

C++




// C++ program to implement toggle and count
// queries on a binary array.
#include<bits/stdc++.h>
using namespace std;
const int MAX = 100000;
 
// segment tree to store count of 1's within range
int tree[MAX] = {0};
 
// bool type tree to collect the updates for toggling
// the values of 1 and 0 in given range
bool lazy[MAX] = {false};
 
// function for collecting updates of toggling
// node --> index of current node in segment tree
// st --> starting index of current node
// en --> ending index of current node
// us --> starting index of range update query
// ue --> ending index of range update query
void toggle(int node, int st, int en, int us, int ue)
{
    // If lazy value is non-zero for current node of segment
    // tree, then there are some pending updates. So we need
    // to make sure that the pending updates are done before
    // making new updates. Because this value may be used by
    // parent after recursive calls (See last line of this
    // function)
    if (lazy[node])
    {
        // Make pending updates using value stored in lazy nodes
        lazy[node] = false;
        tree[node] = en - st + 1 - tree[node];
 
        // checking if it is not leaf node because if
        // it is leaf node then we cannot go further
        if (st < en)
        {
            // We can postpone updating children we don't
            // need their new values now.
            // Since we are not yet updating children of 'node',
            // we need to set lazy flags for the children
            lazy[node<<1] = !lazy[node<<1];
            lazy[1+(node<<1)] = !lazy[1+(node<<1)];
        }
    }
 
    // out of range
    if (st>en || us > en || ue < st)
        return ;
 
    // Current segment is fully in range
    if (us<=st && en<=ue)
    {
        // Add the difference to current node
        tree[node] = en-st+1 - tree[node];
 
        // same logic for checking leaf node or not
        if (st < en)
        {
            // This is where we store values in lazy nodes,
            // rather than updating the segment tree itself
            // Since we don't need these updated values now
            // we postpone updates by storing values in lazy[]
            lazy[node<<1] = !lazy[node<<1];
            lazy[1+(node<<1)] = !lazy[1+(node<<1)];
        }
        return;
    }
 
    // If not completely in range, but overlaps, recur for
    // children,
    int mid = (st+en)/2;
    toggle((node<<1), st, mid, us, ue);
    toggle((node<<1)+1, mid+1,en, us, ue);
 
    // And use the result of children calls to update this node
    if (st < en)
        tree[node] = tree[node<<1] + tree[(node<<1)+1];
}
 
/* node --> Index of current node in the segment tree.
          Initially 0 is passed as root is always at'
          index 0
   st & en  --> Starting and ending indexes of the
                segment represented by current node,
                i.e., tree[node]
   qs & qe  --> Starting and ending indexes of query
                range */
// function to count number of 1's within given range
int countQuery(int node, int st, int en, int qs, int qe)
{
    // current node is out of range
    if (st>en || qs > en || qe < st)
        return 0;
 
    // If lazy flag is set for current node of segment tree,
    // then there are some pending updates. So we need to
    // make sure that the pending updates are done before
    // processing the sub sum query
    if (lazy[node])
    {
        // Make pending updates to this node. Note that this
        // node represents sum of elements in arr[st..en] and
        // all these elements must be increased by lazy[node]
        lazy[node] = false;
        tree[node] = en-st+1-tree[node];
 
        // checking if it is not leaf node because if
        // it is leaf node then we cannot go further
        if (st<en)
        {
            // Since we are not yet updating children os si,
            // we need to set lazy values for the children
            lazy[node<<1] = !lazy[node<<1];
            lazy[(node<<1)+1] = !lazy[(node<<1)+1];
        }
    }
 
    // At this point we are sure that pending lazy updates
    // are done for current node. So we can return value
    // If this segment lies in range
    if (qs<=st && en<=qe)
        return tree[node];
 
    // If a part of this segment overlaps with the given range
    int mid = (st+en)/2;
    return countQuery((node<<1), st, mid, qs, qe) +
           countQuery((node<<1)+1, mid+1, en, qs, qe);
}
 
// Driver program to run the case
int main()
{
    int n = 5;
    toggle(1, 0, n-1, 1, 2);  //  Toggle 1 2
    toggle(1, 0, n-1, 2, 4);  //  Toggle 2 4
 
    cout << countQuery(1, 0, n-1, 2, 3) << endl;  //  Count 2 3
 
    toggle(1, 0, n-1, 2, 4);  //  Toggle 2 4
 
    cout << countQuery(1, 0, n-1, 1, 4) << endl;  //  Count 1 4
 
   return 0;
}
 
 

Java




// Java program to implement toggle and
// count queries on a binary array.
 
class GFG
{
static final int MAX = 100000;
 
// segment tree to store count
// of 1's within range
static int tree[] = new int[MAX];
 
// bool type tree to collect the updates
// for toggling the values of 1 and 0 in
// given range
static boolean lazy[] = new boolean[MAX];
 
// function for collecting updates of toggling
// node --> index of current node in segment tree
// st --> starting index of current node
// en --> ending index of current node
// us --> starting index of range update query
// ue --> ending index of range update query
static void toggle(int node, int st,
                   int en, int us, int ue)
{
    // If lazy value is non-zero for current
    // node of segment tree, then there are
    // some pending updates. So we need
    // to make sure that the pending updates
    // are done before making new updates.
    // Because this value may be used by
    // parent after recursive calls (See last
    // line of this function)
    if (lazy[node])
    {
         
        // Make pending updates using value
        // stored in lazy nodes
        lazy[node] = false;
        tree[node] = en - st + 1 - tree[node];
 
        // checking if it is not leaf node
        // because if it is leaf node then
        // we cannot go further
        if (st < en)
        {
            // We can postpone updating children
            // we don't need their new values now.
            // Since we are not yet updating children
            // of 'node', we need to set lazy flags
            // for the children
            lazy[node << 1] = !lazy[node << 1];
            lazy[1 + (node << 1)] = !lazy[1 + (node << 1)];
        }
    }
 
    // out of range
    if (st > en || us > en || ue < st)
    {
        return;
    }
 
    // Current segment is fully in range
    if (us <= st && en <= ue)
    {
        // Add the difference to current node
        tree[node] = en - st + 1 - tree[node];
 
        // same logic for checking leaf node or not
        if (st < en)
        {
            // This is where we store values in lazy nodes,
            // rather than updating the segment tree itself
            // Since we don't need these updated values now
            // we postpone updates by storing values in lazy[]
            lazy[node << 1] = !lazy[node << 1];
            lazy[1 + (node << 1)] = !lazy[1 + (node << 1)];
        }
        return;
    }
 
    // If not completely in rang,
    // but overlaps, recur for children,
    int mid = (st + en) / 2;
    toggle((node << 1), st, mid, us, ue);
    toggle((node << 1) + 1, mid + 1, en, us, ue);
 
    // And use the result of children
    // calls to update this node
    if (st < en)
    {
        tree[node] = tree[node << 1] +
                     tree[(node << 1) + 1];
    }
}
 
/* node --> Index of current node in the segment tree.
    Initially 0 is passed as root is always at'
    index 0
st & en --> Starting and ending indexes of the
            segment represented by current node,
            i.e., tree[node]
qs & qe --> Starting and ending indexes of query
            range */
// function to count number of 1's
// within given range
static int countQuery(int node, int st,
                      int en, int qs, int qe)
{
    // current node is out of range
    if (st > en || qs > en || qe < st)
    {
        return 0;
    }
 
    // If lazy flag is set for current
    // node of segment tree, then there
    // are some pending updates. So we
    // need to make sure that the pending
    // updates are done before processing
    // the sub sum query
    if (lazy[node])
    {
        // Make pending updates to this node.
        // Note that this node represents sum
        // of elements in arr[st..en] and
        // all these elements must be increased
        // by lazy[node]
        lazy[node] = false;
        tree[node] = en - st + 1 - tree[node];
 
        // checking if it is not leaf node because if
        // it is leaf node then we cannot go further
        if (st < en)
        {
            // Since we are not yet updating children os si,
            // we need to set lazy values for the children
            lazy[node << 1] = !lazy[node << 1];
            lazy[(node << 1) + 1] = !lazy[(node << 1) + 1];
        }
    }
 
    // At this point we are sure that pending
    // lazy updates are done for current node.
    // So we can return value If this segment
    // lies in range
    if (qs <= st && en <= qe)
    {
        return tree[node];
    }
 
    // If a part of this segment overlaps
    // with the given range
    int mid = (st + en) / 2;
    return countQuery((node << 1), st, mid, qs, qe) +
           countQuery((node << 1) + 1, mid + 1, en, qs, qe);
}
 
// Driver Code
public static void main(String args[])
{
    int n = 5;
    toggle(1, 0, n - 1, 1, 2); // Toggle 1 2
    toggle(1, 0, n - 1, 2, 4); // Toggle 2 4
 
    System.out.println(countQuery(1, 0, n - 1, 2, 3)); // Count 2 3
 
    toggle(1, 0, n - 1, 2, 4); // Toggle 2 4
 
    System.out.println(countQuery(1, 0, n - 1, 1, 4)); // Count 1 4
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python program to implement toggle and count
# queries on a binary array.
MAX = 100000
 
# segment tree to store count of 1's within range
tree = [0] * MAX
 
# bool type tree to collect the updates for toggling
# the values of 1 and 0 in given range
lazy = [False] * MAX
 
# function for collecting updates of toggling
# node --> index of current node in segment tree
# st --> starting index of current node
# en --> ending index of current node
# us --> starting index of range update query
# ue --> ending index of range update query
def toggle(node: int, st: int, en: int, us: int, ue: int):
 
    # If lazy value is non-zero for current node of segment
    # tree, then there are some pending updates. So we need
    # to make sure that the pending updates are done before
    # making new updates. Because this value may be used by
    # parent after recursive calls (See last line of this
    # function)
    if lazy[node]:
 
        # Make pending updates using value stored in lazy nodes
        lazy[node] = False
        tree[node] = en - st + 1 - tree[node]
 
        # checking if it is not leaf node because if
        # it is leaf node then we cannot go further
        if st < en:
 
            # We can postpone updating children we don't
            # need their new values now.
            # Since we are not yet updating children of 'node',
            # we need to set lazy flags for the children
            lazy[node << 1] = not lazy[node << 1]
            lazy[1 + (node << 1)] = not lazy[1 + (node << 1)]
 
    # out of range
    if st > en or us > en or ue < st:
        return
 
    # Current segment is fully in range
    if us <= st and en <= ue:
 
        # Add the difference to current node
        tree[node] = en - st + 1 - tree[node]
 
        # same logic for checking leaf node or not
        if st < en:
 
            # This is where we store values in lazy nodes,
            # rather than updating the segment tree itself
            # Since we don't need these updated values now
            # we postpone updates by storing values in lazy[]
            lazy[node << 1] = not lazy[node << 1]
            lazy[1 + (node << 1)] = not lazy[1 + (node << 1)]
        return
 
    # If not completely in rang, but overlaps, recur for
    # children,
    mid = (st + en) // 2
    toggle((node << 1), st, mid, us, ue)
    toggle((node << 1) + 1, mid + 1, en, us, ue)
 
    # And use the result of children calls to update this node
    if st < en:
        tree[node] = tree[node << 1] + tree[(node << 1) + 1]
 
# node --> Index of current node in the segment tree.
#         Initially 0 is passed as root is always at'
#         index 0
# st & en --> Starting and ending indexes of the
#             segment represented by current node,
#             i.e., tree[node]
# qs & qe --> Starting and ending indexes of query
#             range
# function to count number of 1's within given range
def countQuery(node: int, st: int, en: int, qs: int, qe: int) -> int:
 
    # current node is out of range
    if st > en or qs > en or qe < st:
        return 0
 
    # If lazy flag is set for current node of segment tree,
    # then there are some pending updates. So we need to
    # make sure that the pending updates are done before
    # processing the sub sum query
    if lazy[node]:
 
        # Make pending updates to this node. Note that this
        # node represents sum of elements in arr[st..en] and
        # all these elements must be increased by lazy[node]
        lazy[node] = False
        tree[node] = en - st + 1 - tree[node]
 
        # checking if it is not leaf node because if
        # it is leaf node then we cannot go further
        if st < en:
 
            # Since we are not yet updating children os si,
            # we need to set lazy values for the children
            lazy[node << 1] = not lazy[node << 1]
            lazy[(node << 1) + 1] = not lazy[(node << 1) + 1]
 
    # At this point we are sure that pending lazy updates
    # are done for current node. So we can return value
    # If this segment lies in range
    if qs <= st and en <= qe:
        return tree[node]
 
    # If a part of this segment overlaps with the given range
    mid = (st + en) // 2
    return countQuery((node << 1), st, mid, qs, qe) + countQuery(
        (node << 1) + 1, mid + 1, en, qs, qe)
 
# Driver Code
if __name__ == "__main__":
 
    n = 5
    toggle(1, 0, n - 1, 1, 2) # Toggle 1 2
    toggle(1, 0, n - 1, 2, 4) # Toggle 2 4
 
    print(countQuery(1, 0, n - 1, 2, 3)) # count 2 3
 
    toggle(1, 0, n - 1, 2, 4) # Toggle 2 4
 
    print(countQuery(1, 0, n - 1, 1, 4)) # count 1 4
 
# This code is contributed by
# sanjeev2552
 
 

C#




// C# program to implement toggle and
// count queries on a binary array.
using System;
 
public class GFG{
 
    static readonly int MAX = 100000;
 
    // segment tree to store count
    // of 1's within range
    static int []tree = new int[MAX];
 
    // bool type tree to collect the updates
    // for toggling the values of 1 and 0 in
    // given range
    static bool []lazy = new bool[MAX];
 
    // function for collecting updates of toggling
    // node --> index of current node in segment tree
    // st --> starting index of current node
    // en --> ending index of current node
    // us --> starting index of range update query
    // ue --> ending index of range update query
    static void toggle(int node, int st,
                    int en, int us, int ue)
    {
        // If lazy value is non-zero for current
        // node of segment tree, then there are
        // some pending updates. So we need
        // to make sure that the pending updates
        // are done before making new updates.
        // Because this value may be used by
        // parent after recursive calls (See last
        // line of this function)
        if (lazy[node])
        {
 
            // Make pending updates using value
            // stored in lazy nodes
            lazy[node] = false;
            tree[node] = en - st + 1 - tree[node];
 
            // checking if it is not leaf node
            // because if it is leaf node then
            // we cannot go further
            if (st < en)
            {
                // We can postpone updating children
                // we don't need their new values now.
                // Since we are not yet updating children
                // of 'node', we need to set lazy flags
                // for the children
                lazy[node << 1] = !lazy[node << 1];
                lazy[1 + (node << 1)] = !lazy[1 + (node << 1)];
            }
        }
 
        // out of range
        if (st > en || us > en || ue < st)
        {
            return;
        }
 
        // Current segment is fully in range
        if (us <= st && en <= ue)
        {
            // Add the difference to current node
            tree[node] = en - st + 1 - tree[node];
 
            // same logic for checking leaf node or not
            if (st < en)
            {
                // This is where we store values in lazy nodes,
                // rather than updating the segment tree itself
                // Since we don't need these updated values now
                // we postpone updates by storing values in lazy[]
                lazy[node << 1] = !lazy[node << 1];
                lazy[1 + (node << 1)] = !lazy[1 + (node << 1)];
            }
            return;
        }
 
        // If not completely in rang,
        // but overlaps, recur for children,
        int mid = (st + en) / 2;
        toggle((node << 1), st, mid, us, ue);
        toggle((node << 1) + 1, mid + 1, en, us, ue);
 
        // And use the result of children
        // calls to update this node
        if (st < en)
        {
            tree[node] = tree[node << 1] +
                        tree[(node << 1) + 1];
        }
    }
 
    /* node --> Index of current node in the segment tree.
        Initially 0 is passed as root is always at'
        index 0
    st & en --> Starting and ending indexes of the
                segment represented by current node,
                i.e., tree[node]
    qs & qe --> Starting and ending indexes of query
                range */
    // function to count number of 1's
    // within given range
    static int countQuery(int node, int st,
                        int en, int qs, int qe)
    {
        // current node is out of range
        if (st > en || qs > en || qe < st)
        {
            return 0;
        }
 
        // If lazy flag is set for current
        // node of segment tree, then there
        // are some pending updates. So we
        // need to make sure that the pending
        // updates are done before processing
        // the sub sum query
        if (lazy[node])
        {
            // Make pending updates to this node.
            // Note that this node represents sum
            // of elements in arr[st..en] and
            // all these elements must be increased
            // by lazy[node]
            lazy[node] = false;
            tree[node] = en - st + 1 - tree[node];
 
            // checking if it is not leaf node because if
            // it is leaf node then we cannot go further
            if (st < en)
            {
                // Since we are not yet updating children os si,
                // we need to set lazy values for the children
                lazy[node << 1] = !lazy[node << 1];
                lazy[(node << 1) + 1] = !lazy[(node << 1) + 1];
            }
        }
 
        // At this point we are sure that pending
        // lazy updates are done for current node.
        // So we can return value If this segment
        // lies in range
        if (qs <= st && en <= qe)
        {
            return tree[node];
        }
 
        // If a part of this segment overlaps
        // with the given range
        int mid = (st + en) / 2;
        return countQuery((node << 1), st, mid, qs, qe) +
            countQuery((node << 1) + 1, mid + 1, en, qs, qe);
    }
 
    // Driver Code
    public static void Main()
    {
        int n = 5;
        toggle(1, 0, n - 1, 1, 2); // Toggle 1 2
        toggle(1, 0, n - 1, 2, 4); // Toggle 2 4
 
        Console.WriteLine(countQuery(1, 0, n - 1, 2, 3)); // Count 2 3
 
        toggle(1, 0, n - 1, 2, 4); // Toggle 2 4
 
        Console.WriteLine(countQuery(1, 0, n - 1, 1, 4)); // Count 1 4
    }
}
 
/*This code is contributed by PrinciRaj1992*/
 
 

Javascript




<script>
 
// JavaScript program to implement toggle and
// count queries on a binary array.
 
let MAX = 100000;
 
// segment tree to store count
// of 1's within range
let tree=new Array(MAX);
 
// bool type tree to collect the updates
// for toggling the values of 1 and 0 in
// given range
let lazy = new Array(MAX);
 
for(let i=0;i<MAX;i++)
{
    tree[i]=0;
    lazy[i]=false;
}
 
// function for collecting updates of toggling
// node --> index of current node in segment tree
// st --> starting index of current node
// en --> ending index of current node
// us --> starting index of range update query
// ue --> ending index of range update query
function toggle(node,st,en,us,ue)
{
    // If lazy value is non-zero for current
    // node of segment tree, then there are
    // some pending updates. So we need
    // to make sure that the pending updates
    // are done before making new updates.
    // Because this value may be used by
    // parent after recursive calls (See last
    // line of this function)
    if (lazy[node])
    {
           
        // Make pending updates using value
        // stored in lazy nodes
        lazy[node] = false;
        tree[node] = en - st + 1 - tree[node];
   
        // checking if it is not leaf node
        // because if it is leaf node then
        // we cannot go further
        if (st < en)
        {
            // We can postpone updating children
            // we don't need their new values now.
            // Since we are not yet updating children
            // of 'node', we need to set lazy flags
            // for the children
            lazy[node << 1] = !lazy[node << 1];
            lazy[1 + (node << 1)] = !lazy[1 + (node << 1)];
        }
    }
   
    // out of range
    if (st > en || us > en || ue < st)
    {
        return;
    }
   
    // Current segment is fully in range
    if (us <= st && en <= ue)
    {
        // Add the difference to current node
        tree[node] = en - st + 1 - tree[node];
   
        // same logic for checking leaf node or not
        if (st < en)
        {
            // This is where we store values in lazy nodes,
            // rather than updating the segment tree itself
            // Since we don't need these updated values now
            // we postpone updates by storing values in lazy[]
            lazy[node << 1] = !lazy[node << 1];
            lazy[1 + (node << 1)] = !lazy[1 + (node << 1)];
        }
        return;
    }
   
    // If not completely in rang,
    // but overlaps, recur for children,
    let mid = Math.floor((st + en) / 2);
    toggle((node << 1), st, mid, us, ue);
    toggle((node << 1) + 1, mid + 1, en, us, ue);
   
    // And use the result of children
    // calls to update this node
    if (st < en)
    {
        tree[node] = tree[node << 1] +
                     tree[(node << 1) + 1];
    }
}
 
/* node --> Index of current node in the segment tree.
    Initially 0 is passed as root is always at'
    index 0
st & en --> Starting and ending indexes of the
            segment represented by current node,
            i.e., tree[node]
qs & qe --> Starting and ending indexes of query
            range */
// function to count number of 1's
// within given range
function countQuery(node,st,en,qs,qe)
{
    // current node is out of range
    if (st > en || qs > en || qe < st)
    {
        return 0;
    }
   
    // If lazy flag is set for current
    // node of segment tree, then there
    // are some pending updates. So we
    // need to make sure that the pending
    // updates are done before processing
    // the sub sum query
    if (lazy[node])
    {
        // Make pending updates to this node.
        // Note that this node represents sum
        // of elements in arr[st..en] and
        // all these elements must be increased
        // by lazy[node]
        lazy[node] = false;
        tree[node] = en - st + 1 - tree[node];
   
        // checking if it is not leaf node because if
        // it is leaf node then we cannot go further
        if (st < en)
        {
            // Since we are not yet updating children os si,
            // we need to set lazy values for the children
            lazy[node << 1] = !lazy[node << 1];
            lazy[(node << 1) + 1] = !lazy[(node << 1) + 1];
        }
    }
   
    // At this point we are sure that pending
    // lazy updates are done for current node.
    // So we can return value If this segment
    // lies in range
    if (qs <= st && en <= qe)
    {
        return tree[node];
    }
   
    // If a part of this segment overlaps
    // with the given range
    let mid = Math.floor((st + en) / 2);
    return countQuery((node << 1), st, mid, qs, qe) +
           countQuery((node << 1) + 1, mid + 1, en, qs, qe);
}
 
// Driver Code
let n = 5;
toggle(1, 0, n - 1, 1, 2); // Toggle 1 2
toggle(1, 0, n - 1, 2, 4); // Toggle 2 4
 
document.write(countQuery(1, 0, n - 1, 2, 3)+"<br>"); // Count 2 3
 
toggle(1, 0, n - 1, 2, 4); // Toggle 2 4
 
document.write(countQuery(1, 0, n - 1, 1, 4)+"<br>"); // Count 1 4
 
 
// This code is contributed by rag2127
 
</script>
 
 

Output:  

1 2

The time complexity of the given program is O(log n) for both toggle() and countQuery() functions.

The space complexity of the program is O(n).

 



Next Article
Count total set bits in an array

S

Shashank Mishra ( Gullu )
Improve
Article Tags :
  • Advanced Data Structure
  • DSA
  • array-range-queries
  • Segment-Tree
Practice Tags :
  • Advanced Data Structure
  • Segment-Tree

Similar Reads

  • Count 1's in a sorted binary array
    Given a binary array arr[] of size n, which is sorted in non-increasing order, count the number of 1's in it. Examples: Input: arr[] = [1, 1, 0, 0, 0, 0, 0]Output: 2Explanation: Count of the 1's in the given array is 2. Input: arr[] = [1, 1, 1, 1, 1, 1, 1]Output: 7 Input: arr[] = [0, 0, 0, 0, 0, 0,
    8 min read
  • XOR in a range of a binary array
    Given a binary array arr[] of size N and some queries. Each query represents an index range [l, r]. The task is to find the xor of the elements in the given index range for each query i.e. arr[l] ^ arr[l + 1] ^ ... ^ arr[r]. Examples: Input: arr[] = {1, 0, 1, 1, 0, 1, 1}, q[][] = {{0, 3}, {0, 2}} Ou
    7 min read
  • Count total set bits in an array
    Given an array arr, the task is to count the total number of set bits in all numbers of that array arr. Example: Input: arr[] = {1, 2, 5, 7}Output: 7Explanation: Number of set bits in {1, 2, 5, 7} are {1, 1, 2, 3} respectively Input: arr[] = {0, 4, 9, 8}Output: 4 Approach: Follow the below steps to
    5 min read
  • Count number of Inversion in a Binary Array
    Given a Binary Array arr[], the task is to count the number of inversions in it. The number of inversions in an array is the number of pairs of indices i, j such that i < j and a[i] > a[j]. Examples: Input: arr[] = {1, 0, 1, 0, 0, 1, 0}Output: 8Explanation: Pairs of the index (i, j) are (0, 1)
    5 min read
  • Binary array after M range toggle operations
    Consider a binary array consisting of N elements (initially all elements are 0). After that, you are given M commands where each command is of form a b, which means you have to toggle all the elements of the array in range a to b (both inclusive). After the execution of all M commands, you have to f
    6 min read
  • Queries to calculate Bitwise AND of an array with updates
    Given an array arr[] consisting of N positive integers and a 2D array Q[][] consisting of queries of the type {i, val}, the task for each query is to replace arr[i] by val and calculate the Bitwise AND of the modified array. Examples: Input: arr[] = {1, 2, 3, 4, 5}, Q[][] = {{0, 2}, {3, 3}, {4, 2}}O
    15+ min read
  • Count Subarrays of 1 in Binary Array
    Given an array arr[] of size N, the array contains only 1s and 0s, and the task is to return the count of the total number of subarrays where all the elements of the subarrays are 1. Examples: Input: N = 4, arr[] = {1, 1, 1, 0}Output: 6Explanation: Subarrays of 1 will look like the following: [1], [
    13 min read
  • Queries on Left and Right Circular shift on array
    Given an array arr[] of N integers. There are three types of commands: 1 x: Right Circular Shift the array x times. If an array is a[0], a[1], ...., a[n - 1], then after one right circular shift the array will become a[n - 1], a[0], a[1], ...., a[n - 2].2 y: Left Circular Shift the array y times. If
    11 min read
  • Range Update Queries to XOR with 1 in a Binary Array.
    Given a binary array arr[] of size N. The task is to answer Q queries which can be of any one type from below: Type 1 - 1 l r : Performs bitwise xor operation on all the array elements from l to r with 1. Type 2 - 2 l r : Returns the minimum distance between two elements with value 1 in a subarray [
    15+ min read
  • Javascript Program to Count 1's in a sorted binary array
    Given a binary array sorted in non-increasing order, count the number of 1's in it. Examples: Input: arr[] = {1, 1, 0, 0, 0, 0, 0} Output: 2 Input: arr[] = {1, 1, 1, 1, 1, 1, 1} Output: 7 Input: arr[] = {0, 0, 0, 0, 0, 0, 0} Output: 0A simple solution is to traverse the array linearly. The time comp
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences