![]() |
VOOZH | about |
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 = 11Input: str = "110"
Output: 111
Explanation: The substrings of 110 are: 1, 1, 0, 11, 10, 110.
Their XOR = 1 ⊕ 1 ⊕ 0 ⊕ 11 ⊕ 10 ⊕ 110 = 111Input: 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:
Below is the implementation of the above approach:
11001
Time Complexity: O(N)
Auxiliary Space: O(N)