VOOZH about

URL: https://www.geeksforgeeks.org/dsa/xor-of-all-substrings-of-a-given-binary-string/

⇱ XOR of all substrings of a given Binary String - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

XOR of all substrings of a given Binary String

Last Updated : 23 Jul, 2025

Given a binary string str of size N, the task is to calculate the bitwise XOR of all substrings of str.

Examples:

Input: str = "11"
Output: 11
Explanation: The substrings of "11" are: 1, 1,  and 11.
Their XOR = 1 ⊕ 1 ⊕ 11 = 11

Input: str = "110"
Output: 111
Explanation: The substrings of 110 are: 1, 1, 0, 11, 10, 110. 
Their XOR = 1 ⊕ 1 ⊕ 0 ⊕ 11 ⊕ 10 ⊕ 110 = 111

Input: str = "10101"
Output: 11001
Explanation: The substrings of 10101 are: 1, 10, 101, 1010, 10101, 0, 01, 010, 0101, 1, 10, 101, 0, 01, and 1.
Their XOR = 1 ⊕ 10 ⊕ 101 ⊕ 1010 ⊕ 10101 ⊕ 0 ⊕ 01 ⊕ 010 ⊕ 0101 ⊕ 1 ⊕ 10 ⊕ 101 ⊕ 0 ⊕ 01 ⊕ 1 = 11001

Approach: This problem can be solved based on the following observation:

XOR of odd number of 1s is always 1. Otherwise, the XOR is 0. 
Each jth bit can be the ith bit in a substring when 0 ≤ j ≤ N-i.
So each character has contribution for the last bit (LSB) of the result. 
All characters from i = 0 to N-2 has contribution for 2nd last bit and so on.

Follow the steps mentioned below to utilize the above observation to solve this problem:

  • Create an array (say occurrence[]) to store the total count of 1s having contribution for ith index from LSB end in resultant XOR.
  • Now iterate from the LSB end (iterator i):
    • If the total number of 1s at ith index is odd then the resultant XOR will have ith bit from the LSB end as 1.
    • Otherwise, the value in ith bit will be 0.
  • Return the resultant XOR.

Below is the implementation of the above approach:


Output
11001

Time Complexity: O(N)
Auxiliary Space: O(N)

Comment