Binary array after M range toggle operations
Last Updated :
19 Sep, 2023
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 find the resultant array.
Examples:
Input : N = 5, M = 3
C1 = 1 3, C2 = 4 5, C3 = 1 4
Output : Resultant array = {0, 0, 0, 0, 1}
Explanation :
Initial array : {0, 0, 0, 0, 0}
After first toggle : {1, 1, 1, 0, 0}
After second toggle : {1, 1, 1, 1, 1}
After third toggle : {0, 0, 0, 0, 1}
Input : N = 5, M = 5
C1 = 1 5, C2 = 1 5, C3 = 1 5,
C4 = 1 5, C5 = 1 5
Output : Resultant array = {1, 1, 1, 1, 1}
Naive Approach: For the given N we should create a bool array of n+1 elements and for each of M commands we have to iterate from a to b and toggle all elements in the range of a to b with help of XOR.
The complexity of this approach is O(n^2).
for (int i = 1; i > a >> b;
for (int j = a; j <= b; j++)
arr[j] ^= 1;
Efficient Approach: The idea is based on the sample problem discussed in the Prefix Sum Array article. For the given n, we create a bool array of n+2 elements and for each of M commands, we have to just toggle elements a and b+1 with help of XOR. After all commands we will process the array as arr[i] ^= arr[i-1];
The complexity of this approach is O(n).
Implementation:
C++
// CPP program to find modified array after
// m range toggle operations.
#include<bits/stdc++.h>
using namespace std;
// function for toggle
void command(bool arr[], int a, int b)
{
arr[a] ^= 1;
arr[b+1] ^= 1;
}
// function for final processing of array
void process(bool arr[], int n)
{
for (int k=1; k<=n; k++)
arr[k] ^= arr[k-1];
}
// function for printing result
void result(bool arr[], int n)
{
for (int k=1; k<=n; k++)
cout << arr[k] <<" ";
}
// driver program
int main()
{
int n = 5, m = 3;
bool arr[n+2] = {0};
// function call for toggle
command(arr, 1, 5);
command(arr, 2, 5);
command(arr, 3, 5);
// process array
process(arr, n);
// print result
result(arr, n);
return 0;
}
Java
// Java program to find modified array
// after m range toggle operations.
class GFG
{
// function for toggle
static void command(boolean arr[],
int a, int b)
{
arr[a] ^= true;
arr[b + 1] ^= true;
}
// function for final processing of array
static void process(boolean arr[], int n)
{
for (int k = 1; k <= n; k++)
{
arr[k] ^= arr[k - 1];
}
}
// function for printing result
static void result(boolean arr[], int n)
{
for (int k = 1; k <= n; k++)
{
if(arr[k] == true)
System.out.print("1" + " ");
else
System.out.print("0" + " ");
}
}
// Driver Code
public static void main(String args[])
{
int n = 5, m = 3;
boolean arr[] = new boolean[n + 2];
// function call for toggle
command(arr, 1, 5);
command(arr, 2, 5);
command(arr, 3, 5);
// process array
process(arr, n);
// print result
result(arr, n);
}
}
// This code is contributed
// by PrinciRaj1992
Python3
# Python 3 program to find modified array after
# m range toggle operations.
# function for toggle
def command(brr, a, b):
arr[a] ^= 1
arr[b+1] ^= 1
# function for final processing of array
def process(arr, n):
for k in range(1, n + 1, 1):
arr[k] ^= arr[k - 1]
# function for printing result
def result(arr, n):
for k in range(1, n + 1, 1):
print(arr[k], end = " ")
# Driver Code
if __name__ == '__main__':
n = 5
m = 3
arr = [0 for i in range(n+2)]
# function call for toggle
command(arr, 1, 5)
command(arr, 2, 5)
command(arr, 3, 5)
# process array
process(arr, n)
# print result
result(arr, n)
# This code is contributed by
# Surendra_Gangwar
C#
// C# program to find modified array
// after m range toggle operations.
using System;
class GFG
{
// function for toggle
static void command(bool[] arr,
int a, int b)
{
arr[a] ^= true;
arr[b + 1] ^= true;
}
// function for final processing of array
static void process(bool[] arr, int n)
{
for (int k = 1; k <= n; k++)
{
arr[k] ^= arr[k - 1];
}
}
// function for printing result
static void result(bool[] arr, int n)
{
for (int k = 1; k <= n; k++)
{
if(arr[k] == true)
Console.Write("1" + " ");
else
Console.Write("0" + " ");
}
}
// Driver Code
public static void Main()
{
int n = 5, m = 3;
bool[] arr = new bool[n + 2];
// function call for toggle
command(arr, 1, 5);
command(arr, 2, 5);
command(arr, 3, 5);
// process array
process(arr, n);
// print result
result(arr, n);
}
}
// This code is contributed
// by Akanksha Rai
PHP
<?php
// PHP program to find modified array
// after m range toggle operations.
// function for toggle
function command($arr, $a, $b)
{
$arr[$a] = $arr[$a] ^ 1;
$arr[$b + 1] ^= 1;
}
// function for final processing
// of array
function process($arr, $n)
{
for ($k = 1; $k <= $n; $k++)
{
$arr[$k] = $arr[$k] ^ $arr[$k - 1];
}
}
// function for printing result
function result($arr, $n)
{
for ($k = 1; $k <= $n; $k++)
echo $arr[$k] . " ";
}
// Driver Code
$n = 5; $m = 3;
$arr = new SplFixedArray(7);
$arr[6] = array(0);
// function call for toggle
command($arr, 1, 5);
command($arr, 2, 5);
command($arr, 3, 5);
// process array
process($arr, $n);
// print result
result($arr, $n);
// This code is contributed
// by Mukul Singh
?>
JavaScript
<script>
// Javascript program to find modified array after
// m range toggle operations.
// function for toggle
function command(arr, a, b)
{
arr[a] ^= 1;
arr[b+1] ^= 1;
}
// function for final processing of array
function process( arr, n)
{
for (var k=1; k<=n; k++)
arr[k] ^= arr[k-1];
}
// function for printing result
function result( arr, n)
{
for (var k=1; k<=n; k++)
document.write( arr[k] + " ");
}
// driver program
var n = 5, m = 3;
var arr = Array(n+2).fill(0);
// function call for toggle
command(arr, 1, 5);
command(arr, 2, 5);
command(arr, 3, 5);
// process array
process(arr, n);
// print result
result(arr, n);
</script>
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem