Open In App

Binary array after M range toggle operations

Last Updated : 19 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Share
2 Likes
Like
Report

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++
Java Python3 C# PHP JavaScript

Output
1 0 1 1 1 

Time Complexity: O(n)
Auxiliary Space: O(1)

 


Practice Tags :

Similar Reads