- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Binary array after M range toggle operations?
Here we will see one problem. We have one binary array. It has n elements. Each element will be either 0 or 1. Initially, all elements are 0. Now we will provide M commands. Each command will contain start and end indices. So command(a, b) is indicating that the command will be applied from element at position a to element at position b. The command will toggle the values. So it will toggle from ath index to bth index. This problem is simple. check the algorithm to get the concept.
Algorithm
toggleCommand(arr, a, b)
Begin for each element e from index a to b, do toggle the e and place into arr at its position. done End
Example
#include <iostream> using namespace std; void toggleCommand(int arr[], int a, int b){ for(int i = a; i <= b; i++){ arr[i] ^= 1; //toggle each bit in range a to b } } void display(int arr[], int n){ for(int i = 0; i<n; i++){ cout << arr[i] << " "; } cout << endl; } int main() { int arr[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; int n = sizeof(arr)/sizeof(arr[0]); display(arr, n); toggleCommand(arr, 3, 6); toggleCommand(arr, 8, 10); toggleCommand(arr, 2, 7); display(arr, n); }
Output
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 1 1 1 0
Advertisements
To Continue Learning Please Login
Login with Google