Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Number of substrings of a string
Next article icon

XOR of all substrings of a given Binary String

Last Updated : 31 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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>
 
 
Output
11001

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



Next Article
Number of substrings of a string

P

phasing17
Improve
Article Tags :
  • Bit Magic
  • DSA
  • Strings
  • binary-string
  • Bitwise-XOR
  • substring
Practice Tags :
  • Bit Magic
  • Strings

Similar Reads

  • All substrings of a given String
    Given a string s, containing lowercase alphabetical characters. The task is to print all non-empty substrings of the given string. Examples : Input : s = "abc"Output : "a", "ab", "abc", "b", "bc", "c" Input : s = "ab"Output : "a", "ab", "b" Input : s = "a"Output : "a" [Expected Approach] - Using Ite
    9 min read
  • 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
  • Number of substrings of a string
    Find total number of non-empty substrings of a string with N characters. Input : str = "abc" Output : 6 Every substring of the given string : "a", "b", "c", "ab", "bc", "abc" Input : str = "abcd" Output : 10 Every substring of the given string : "a", "b", "c", "d", "ab", "bc", "cd", "abc", "bcd" and
    3 min read
  • Maximum bitwise OR one of any two Substrings of given Binary String
    Given a binary string str, the task is to find the maximum possible OR value of any two substrings of the binary string str. Examples: Input: str = "1110010"Output: "1111110"Explanation: On choosing the substring "1110010" and "11100" we get the OR value as "1111110" which is the maximum value. Inpu
    8 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
  • Find frequency of all characters across all substrings of given string
    Given a string S containing all lowercase characters and its length N. Find frequency of all characters across all substrings of the given string. Examples: Input: N = 3, S = "aba"Output: a 6b 4Explanation: The substrings are: a, b, a, ab, ba, aba. The frequency of each character: a = 6, b = 4. Henc
    4 min read
  • Count substrings of a given string whose anagram is a palindrome
    Given a string S of length N containing only lowercase alphabets, the task is to print the count of substrings of the given string whose anagram is palindromic. Examples: Input: S = "aaaa"Output: 10Explanation:Possible substrings are {"a", "a", "a", "a", "aa", "aa", "aa", "aaa", "aaa", "aaaa"}. Sinc
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences