Binary array after M range toggle operations?

In C, we can solve the binary array toggle problem by applying range operations on an initially zero-filled array. Given an array of size n (initially all zeros) and M toggle commands, each command toggles all bits in a specified range [a, b]. This problem demonstrates bit manipulation using the XOR operation.

Syntax

void toggleCommand(int arr[], int start, int end);
// Toggles bits from index start to end (inclusive)

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

Here's a complete C program that demonstrates the binary array toggle operations −

#include <stdio.h>

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++) {
        printf("%d ", arr[i]);
    }
    printf("<br>");
}

int main() {
    int arr[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    int n = sizeof(arr)/sizeof(arr[0]);
    
    printf("Initial array: ");
    display(arr, n);
    
    /* Apply toggle commands */
    toggleCommand(arr, 3, 6);
    printf("After toggle(3,6): ");
    display(arr, n);
    
    toggleCommand(arr, 8, 10);
    printf("After toggle(8,10): ");
    display(arr, n);
    
    toggleCommand(arr, 2, 7);
    printf("After toggle(2,7): ");
    display(arr, n);
    
    return 0;
}
Initial array: 0 0 0 0 0 0 0 0 0 0 0 0 
After toggle(3,6): 0 0 0 1 1 1 1 0 0 0 0 0 
After toggle(8,10): 0 0 0 1 1 1 1 0 1 1 1 0 
After toggle(2,7): 0 0 1 0 0 0 0 1 1 1 1 0

How It Works

  • The XOR operation (^= 1) toggles bits: 0 becomes 1 and 1 becomes 0
  • Each toggle command affects all elements in the specified range [start, end]
  • Multiple overlapping operations may cancel each other out in overlapping regions

Key Points

  • Time complexity: O(M × K) where M is number of commands and K is average range size
  • Space complexity: O(1) auxiliary space
  • Array indices are 0-based in this implementation

Conclusion

Binary array toggle operations efficiently use XOR bit manipulation to flip values in specified ranges. This approach provides a simple solution for range-based toggle queries on binary arrays.

Updated on: 2026-03-15T11:19:31+05:30

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements