XOR of all substrings of a given Binary String
Last Updated :
31 May, 2022
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:
C++
// C++ code to implement above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the XOR
string totalXOR(string s, int n)
{
// Vector for storing the occurrences
vector<int> occurrence;
for (int i = 0; i < n; i++) {
if (s[i] == '1')
occurrence.push_back(i + 1);
else
occurrence.push_back(0);
}
// Calculating the total occurrences
// of nth bit
int sums
= accumulate(occurrence.begin(),
occurrence.end(), 0);
string ans = "";
for (int i = 0; i < n; i++) {
// Checking if the total occurrences
// are odd
if (sums % 2 == 1)
ans = "1" + ans;
else
ans = "0" + ans;
sums -= occurrence.back();
occurrence.pop_back();
}
return ans;
}
// Driver Code
int main()
{
int N = 5;
string str = "10101";
cout << totalXOR(str, N);
return 0;
}
Java
// Java program to implement the approach
import java.io.*;
import java.util.ArrayList;
public class GFG {
// function to find XOR
static String totalXOR(String s, int n)
{
// initializing occurrence list
ArrayList<Integer> occurrence
= new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
if ((s.charAt(i)) == '1')
occurrence.add(i + 1);
else
occurrence.add(0);
}
// calculating sum of occurrence
int sums = 0;
for (int i : occurrence)
sums += i;
String ans = "";
for (int i = 0; i < n; i++) {
// Checking if the total occurrences
// are odd
if (sums % 2 == 1)
ans = "1" + ans;
else
ans = "0" + ans;
// subtracting last element of occurrence from
// sums
sums -= occurrence.get(occurrence.size() - 1);
// removing last element of occurrence
occurrence.remove(occurrence.size() - 1);
}
return ans;
}
// Driver Code
public static void main(String[] args)
{
int N = 5;
String str = "10101";
System.out.print(totalXOR(str, N));
}
}
// This code is contributed by phasing17
Python3
# Python Program to implement
# above approach
def totalXOR(string, n):
# Storing the occurrences of 1s
occurrences = [i + 1 if string[i] ==
'1' else 0 for i in range(n)]
# Calculating the occurrences for nth bit
sums = sum(occurrences)
ans = ''
for i in range(n):
ans \
= ['0', '1'][sums % 2 == 1] + ans
# Subtracting the occurrences of
# (i + 1)th bit from ith bit
sums -= occurrences[-1]
del occurrences[-1]
return ans
# Driver Code
if __name__ == '__main__':
N = 5
str = "10101"
print(totalXOR(str, N))
C#
// C# program to implement the approach
using System;
using System.Collections;
public class GFG{
// function to find XOR
static string totalXOR(string s, int n)
{
// initializing occurrence list
ArrayList occurrence
= new ArrayList();
for (int i = 0; i < n; i++) {
if (s[i] == '1')
occurrence.Add(i + 1);
else
occurrence.Add(0);
}
// calculating sum of occurrence
int sums = 0;
foreach (var i in occurrence)
sums = sums + (int)i;
string ans = "";
for (int i = 0; i < n; i++) {
// Checking if the total occurrences
// are odd
if (sums % 2 == 1)
ans = "1" + ans;
else
ans = "0" + ans;
// subtracting last element of occurrence from
// sums
sums = sums - (int)occurrence[occurrence.Count - 1];
// removing last element of occurrence
occurrence.RemoveAt(occurrence.Count - 1);
}
return ans;
}
// Driver Code
static public void Main (){
int N = 5;
string str = "10101";
Console.Write(totalXOR(str, N));
}
}
// This code is contributed by hrithikgarg03188.
JavaScript
<script>
// JavaScript code to implement above approach
// Function to find the XOR
const totalXOR = (s, n) => {
// Vector for storing the occurrences
let occurrence = [];
for (let i = 0; i < n; i++) {
if (s[i] == '1')
occurrence.push(i + 1);
else
occurrence.push(0);
}
// Calculating the total occurrences
// of nth bit
let sums = 0;
for (let itm in occurrence) sums += occurrence[itm];
let ans = "";
for (let i = 0; i < n; i++) {
// Checking if the total occurrences
// are odd
if (sums % 2 == 1)
ans = "1" + ans;
else
ans = "0" + ans;
sums -= occurrence[occurrence.length - 1];
occurrence.pop();
}
return ans;
}
// Driver Code
let N = 5;
let str = "10101";
document.write(totalXOR(str, N));
// This code is contributed by rakeshsahni
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Count of substrings of a given Binary string with all characters same Given binary string str containing only 0 and 1, the task is to find the number of sub-strings containing only 1s and 0s respectively, i.e all characters same. Examples: Input: str = â011âOutput: 4Explanation: Three sub-strings are "1", "1", "11" which have only 1 in them, and one substring is there
10 min read
Number of alternating substrings from a given Binary String Given a binary string of size N, the task is to count the number of alternating substrings that are present in the string S. Examples: Input: S = "0010"Output: 7Explanation: All the substring of the string S are: {"0", "00", "001", "0010", "0", "01", "010", "1", "10", "0"}Strings that are alternatin
13 min read
Find the longest Substring of a given String S Given a string S of length, N. Find the maximum length of any substring of S such that, the bitwise OR of all the characters of the substring is equal to the bitwise OR of the remaining characters of the string. If no such substring exists, print -1. Examples: Input: S = "2347"Output: 3?Explanation:
10 min read
Count of substrings of a Binary string containing only 1s Given a binary string of length N, we need to find out how many substrings of this string contain only 1s. Examples: Input: S = "0110111"Output: 9Explanation:There are 9 substring with only 1's characters. "1" comes 5 times. "11" comes 3 times. "111" comes 1 time. Input: S = "000"Output: 0 The_Appro
6 min read
Count of substrings of a binary string containing K ones Given a binary string of length N and an integer K, we need to find out how many substrings of this string are exist which contains exactly K ones. Examples: Input : s = â10010â K = 1 Output : 9 The 9 substrings containing one 1 are, â1â, â10â, â100â, â001â, â01â, â1â, â10â, â0010â and â010âRecommen
7 min read