The Wayback Machine - https://web.archive.org/web/20240913185325/https://www.geeksforgeeks.org/ways-remove-one-element-binary-string-xor-becomes-zero/
Open In App

Ways to remove one element from a binary string so that XOR becomes zero

Last Updated : 25 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a binary string, task is to erase exactly one integer in the array so that the XOR of the remaining numbers is zero. The task is to count number of ways to remove one element so that XOR of that string become ZERO.

Examples : 

Input : 10000
Output : 1
We only have 1 ways to 

Input : 10011
Output : 3
There are 3 ways to make XOR 0. We
can remove any of the three 1's.

Input : 100011100
Output : 5
There are 5 ways to make XOR 0. We
can remove any of the given 0's

A simple solution is to one by one remove an element, then compute XOR of remaining string. And count occurrences where removing an element makes XOR 0.

An efficient solution is based on following fact. If count of 1s is odd, then we must remove a 1 to make count 0 and we can remove any of the 1s. If count of 1s is even, then XOR is 0, We can remove any of the 0s and XOR will remain 0.

Implementation:

C++




// C++ program to count number of ways to
// remove an element so that XOR of remaining
// string becomes 0.
#include <bits/stdc++.h>
using namespace std;
 
// Return number of ways in which XOR become ZERO
// by remove 1 element
int xorZero(string str)
{
    int one_count = 0, zero_count = 0;
    int n = str.length();
 
    // Counting number of 0 and 1
    for (int i = 0; i < n; i++)
        if (str[i] == '1')
            one_count++;
        else
            zero_count++;
     
    // If count of ones is even
    // then return count of zero
    // else count of one
    if (one_count % 2 == 0)
        return zero_count;
    return one_count;
}
 
// Driver Code
int main()
{
    string str = "11111";
    cout << xorZero(str) << endl;
    return 0;
}


Java




// Java program to count number of ways to
// remove an element so that XOR of remaining
// string becomes 0.
import java.util.*;
  
class CountWays
{
    // Returns number of ways in which XOR become
    // ZERO by remove 1 element
    static int xorZero(String s)
    {
        int one_count = 0, zero_count = 0;
        char[] str=s.toCharArray();
        int n = str.length;
      
        // Counting number of 0 and 1
        for (int i = 0; i < n; i++)
            if (str[i] == '1')
                one_count++;
            else
                zero_count++;
          
        // If count of ones is even
        // then return count of zero
        // else count of one
        if (one_count % 2 == 0)
            return zero_count;
        return one_count;
    }
 
    // Driver Code to test above function
    public static void main(String[] args)
    {
        String s = "11111";
        System.out.println(xorZero(s)); 
    }
}
 
// This code is contributed by Mr. Somesh Awasthi


Python3




# Python 3 program to count number of
# ways to remove an element so that
# XOR of remaining string becomes 0.
 
# Return number of ways in which XOR
# become ZERO by remove 1 element
def xorZero(str):
    one_count = 0
    zero_count = 0
    n = len(str)
 
    # Counting number of 0 and 1
    for i in range(0, n, 1):
        if (str[i] == '1'):
            one_count += 1
        else:
            zero_count += 1
     
    # If count of ones is even
    # then return count of zero
    # else count of one
    if (one_count % 2 == 0):
        return zero_count
    return one_count
 
# Driver Code
if __name__ == '__main__':
    str = "11111"
    print(xorZero(str))
 
# This code is contributed by
# Surendra_Gangwar


C#




// C# program to count number
// of ways to remove an element
// so that XOR of remaining
// string becomes 0.
using System;
 
class GFG
{
    // Returns number of ways
    // in which XOR become
    // ZERO by remove 1 element
    static int xorZero(string s)
    {
        int one_count = 0,
            zero_count = 0;
         
        int n = s.Length;
     
        // Counting number of 0 and 1
        for (int i = 0; i < n; i++)
            if (s[i] == '1')
                one_count++;
            else
                zero_count++;
         
        // If count of ones is even
        // then return count of zero
        // else count of one
        if (one_count % 2 == 0)
            return zero_count;
        return one_count;
    }
 
    // Driver Code
    public static void Main()
    {
        string s = "11111";
        Console.WriteLine(xorZero(s));
    }
}
 
// This code is contributed by anuj_67.


PHP




<?php
// PHP program to count number
// of ways to remove an element
// so that XOR of remaining
// string becomes 0.
 
// Return number of ways in
// which XOR become ZERO
// by remove 1 element
 
function xorZero($str)
{
    $one_count = 0; $zero_count = 0;
    $n = strlen($str);
 
    // Counting number of 0 and 1
    for ($i = 0; $i < $n; $i++)
        if ($str[$i] == '1')
            $one_count++;
        else
            $zero_count++;
     
    // If count of ones is even
    // then return count of zero
    // else count of one
    if ($one_count % 2 == 0)
        return $zero_count;
    return $one_count;
}
 
// Driver Code
$str = "11111";
echo xorZero($str),"\n";
 
// This code is contributed by aj_36
?>


Javascript




<script>
    // Javascript program to count number
    // of ways to remove an element
    // so that XOR of remaining
    // string becomes 0.
     
    // Returns number of ways
    // in which XOR become
    // ZERO by remove 1 element
    function xorZero(s)
    {
        let one_count = 0, zero_count = 0;
           
        let n = s.length;
       
        // Counting number of 0 and 1
        for (let i = 0; i < n; i++)
            if (s[i] == '1')
                one_count++;
            else
                zero_count++;
           
        // If count of ones is even
        // then return count of zero
        // else count of one
        if (one_count % 2 == 0)
            return zero_count;
        return one_count;
    }
     
    let s = "11111";
      document.write(xorZero(s));
 
</script>


Output

5

Time complexity : O(n) //since one traversal of the String is required to complete all operations hence overall time required by the algorithm is linear
Auxiliary Space : O(1) // since no extra array is used so the space taken by the algorithm is constant

 

 



Similar Reads

Number of ways to erase exactly one element in the Binary Array to make XOR zero
Given a binary array of 0's and 1's, the task is to find the number of ways to erase exactly one element from this array to make XOR zero.Examples: Input: arr = {1, 1, 1, 1, 1 } Output: 5 You can erase any of the given 5 1's, it will make the XOR of the rest equal to zero. Input: arr = {1, 0, 0, 1, 0 } Output: 3 Since the XOR of array is already 0,
7 min read
Remove characters from a numeric string such that string becomes divisible by 8
Given a non-negative integer represented in the form of a numeric string str. Remove zero or more characters from the string such that the number becomes divisible by 8. If it is possible, print the string after removing the characters otherwise print -1.Examples: Input: str = "3454" Output: 344 After removing '5', string becomes 344 which is divis
6 min read
Minimize value of a in series a, a/b^1, a/b^2, a/b^3, ..., a/b^n such that sum of initial non-zero terms becomes at least S
Given two integers b and S. The task is to find the minimum value of 'a' such that sum of becomes equal or greater than 'S' for initial non-zero terms. a, a/b1, a/b2, a/b3, ............., a/bn Example: Input: b = 2, S = 4Output: 3Explanation: Let a = 1, S = 1/20 + 1/21 = 1 + 0 = 1 &lt; 4.Let a =2, S = 2/20 + 2/21 + 2/22 = 2 + 1 + 0 = 3 &lt; 4.Let a
8 min read
Remove all zero-rows and all zero-columns from a Matrix
Given a matrix arr[][] of size N * M, the task is to print the matrix after removing all rows and columns from the matrix which consists of 0s only. Examples: Input: arr[][] ={ { 1, 1, 0, 1 }, { 0, 0, 0, 0 }, { 1, 1, 0, 1}, { 0, 1, 0, 1 } } Output: 111 111 011 Explanation: Initially, the matrix is as follows: arr[][] = { { 1, 1, 0, 1 }, { 0, 0, 0,
15+ min read
Check if XOR of each connected component becomes equal after removing atmost P edges
Given, a Tree with N nodes, and an integer P, the task is to remove at edges in range [1, P) and find the XOR of nodes for every connected component formed. If node's values come out to be equal for all connected components formed, Print "YES" else "NO". Examples: Input: N = 5, P = 5, Edges[][]={ { 1, 2 }, { 2, 3 }, { 1, 4 }, { 4, 5 }}, nodes[] = {
15+ min read
Remove one element to get maximum XOR
Given an array arr[] of N elements, the task is to remove one element from the array such that the XOR value of the array is maximized. Print the maximized value.Examples: Input: arr[] = {1, 1, 3} Output: 2 All possible ways of deleting one element and their corresponding XOR values will be: a) Remove 1 -&gt; (1 XOR 3) = 2 b) Remove 1 -&gt; (1 XOR
5 min read
Count ways to change direction of edges such that graph becomes acyclic
Given a directed and unweighted graph consisting of N vertices and an array arr[] where ith vertex has a directed edge to arr[i]. The task is to find the number of ways to change the direction of edges such that the given graph is acyclic. Examples: Input: N = 3, arr[] = {2, 3, 1} The directed graph form by the given information is: Output: 6 Expla
12 min read
Count distinct ways to replace array elements such that product of the array becomes even
Given an array arr[] consisting of N odd integers, the task is to count the different number of ways to make the product of all array elements even, by repeatedly changing any set of elements to any values. Since the count can be very large, print it to modulo 109 + 7. Examples: Input: arr[] = {1, 3}Output: 3Explanation: All possible ways to make t
6 min read
Count of subarrays in range [L, R] having XOR + 1 equal to XOR (XOR) 1 for M queries
Given an array, arr[] of N positive integers and M queries which consist of two integers [Li, Ri] where 1 ? Li ? Ri ? N. For each query, find the number of subarrays in range [Li, Ri] for which (X+1)=(X?1) where X denotes the xor of a subarray. Input: arr[]= {1, 2, 9, 8, 7}, queries[] = {{1, 5}, {3, 4}}Output: 6 1Explanation: Query 1: L=1, R=5: sub
12 min read
Remove minimum elements from the array such that 2*min becomes more than max
Given an array of size N. The task is to remove minimum elements from the array such that twice of minimum number is greater than the maximum number in the modified array. Print the minimum number of elements removed.Examples: Input: arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200} Output: 4 Remove 4 elements (4, 5, 100, 200) so that 2*min becomes more
6 min read
Remove minimum elements from either side such that 2*min becomes more than max
Given an unsorted array, trim the array such that twice of minimum is greater than maximum in the trimmed array. Elements should be removed either end of the array.Number of removals should be minimum. Examples: arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200} Output: 4 We need to remove 4 elements (4, 5, 100, 200) so that 2*min becomes more than max. a
15+ min read
Remove minimum elements from either side such that 2*min becomes more than max | Set 2
Given an unsorted array, trim the array such that twice of minimum is greater than the maximum in the trimmed array. Elements should be removed from either end of the array. The number of removals should be minimum. Examples: Input: arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200} Output: 4 We need to remove 4 elements (4, 5, 100, 200) so that 2*min bec
15+ min read
Print all the root-to-leaf paths of a Binary Tree whose XOR is non-zero
Given a Binary Tree, the task is to print all root-to-leaf paths of this tree whose xor value is non-zero. Examples: Input: 10 / \ 10 3 / \ 10 3 / \ / \ 7 3 42 13 / 7 Output: 10 3 10 7 10 3 3 42 Explanation: All the paths in the given binary tree are : {10, 10} xor value of the path is = 10 ^ 10 = 0 {10, 3, 10, 7} xor value of the path is = 10 ^ 3
11 min read
Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)
Given a function 'int f(unsigned int x)' which takes a non-negative integer 'x' as input and returns an integer as output. The function is monotonically increasing with respect to the value of x, i.e., the value of f(x+1) is greater than f(x) for every input x. Find the value 'n' where f() becomes positive for the first time. Since f() is monotonic
11 min read
Find total number of Permutations such that every element becomes an Extrema
Given an array arr[] of size N non-negative integers, the task is to find the total number of permutations of arr[] such that each element in the array is either strictly greater or smaller than all the elements before it i.e., arr[i] = min(arr[1], arr[2], ..., arr[i - 1]) or arr[i] = max(arr[1], arr[2], ..., arr[i - 1]). Examples: Input: arr[] = {
8 min read
Adding elements of an array until every element becomes greater than or equal to k
We are given a list of N unsorted elements, we need to find the minimum number of steps in which the elements of the list can be added to make all the elements greater than or equal to K. We are allowed to add two elements together and make them one. Examples: Input: arr[] = {1 10 12 9 2 3} K = 6 Output: 2 Explanation: First we add (1 + 2), now the
15+ min read
Number of positions where a letter can be inserted such that a string becomes palindrome
Given a string str, we need to find the no. of positions where a letter(lowercase) can be inserted so that string becomes a palindrome. Examples: Input : str = "abca" Output : possible palindromic strings: 1) acbca (at position 2) 2) abcba (at position 4) Hence, the output is 2. Input : str = "aaa" Output : possible palindromic strings: 1) aaaa 2)
11 min read
Replace '?' in string with zero or one
Given a binary string consisting of 0s and 1s and '?' characters and an integer K, it is allowed to replace '?' with 0 or 1, the task is to check if there is a unique way of replacing '?' with 0s and 1s such that there is only 1 substring of K length containing all 1s. If there is only one way to do so print "Yes" otherwise "No" in all other cases.
8 min read
Count ways to make Bitwise XOR of odd and even indexed elements equal by removing an array element
Given an array arr[] of length N, the task is to find the count of array indices such that removing an element from these indices makes the Bitwise xor of odd-indexed elements and even-indexed (1-based indexing) elements are equal. Examples: Input: arr[] = {1, 0, 1, 0, 1}, N = 5Output: 3Explanation: Removing an element from index 3 modifies arr[] t
10 min read
Find the next non-zero Array element to the right of each array element
Given an array arr[] of N integers, the task is to find the next non-zero array element to the right of every array element. If there doesn't exist any non-zero element, then print that element itself. Examples: Input: arr[] = {1, 2, 0}Output: {2, 2, 0}Explanation:For each array element the next non-zero elements are:arr[0] = 1 -&gt; 2arr[1] = 2 -
6 min read
Number of unique triplets whose XOR is zero
Given N numbers with no duplicates, count the number of unique triplets (ai, aj, ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in the triplet are unique. Examples: Input : a[] = {1, 3, 5, 10, 14, 15};Output : 2 Explanation : {1, 14, 15} and {5, 10, 15} are the unique triplets whose XOR is 0. {1, 14, 15} an
11 min read
Find all possible triangles with XOR of sides zero
Given an integer N, we need to find three integers(X, Y, Z) which can form a triangle with the following conditions: Lengths of sides are integers not exceeding N.XOR of three sides is 0, i.e., X ^ Y ^ Z = 0Area of triangle is greater than 0. Find all the possible triples which satisfy the above conditions. Examples: Input: 6 Output: 6 5 3 Input: 1
6 min read
Maximize the number of subarrays with XOR as zero
Given an array of N numbers. The task is to maximize the number of subarrays with XOR value zero by swapping the bits of an array element of any given subarray any number of times. Note: 1&lt;=A[i]&lt;=1018 Examples: Input: a[] = {6, 7, 14} Output : 2 2 subarrays are {7, 14} and {6, 7 and 14} by swapping their bits individually in subarrays. Subarr
11 min read
Check if the Xor of the frequency of all digits of a number N is zero or not
Given a number N, the task is to check if the xor value of the frequency of the digits is zero or not. Examples: Input: N = 122233 Output: Yes Frequencies of 1, 2 and 3 are 1, 3, 2 respectively. And Xor of 1, 3 and 2 is 0. Input: N = 123 Output: No Approach: Count the frequency of all the digits and then iterate over all frequency and xor them if t
5 min read
Check if a number from every row can be selected such that xor of the numbers is greater than zero
Given a 2-D array of order N X M array elements, the task is to check if we can select a number from every row in such a way that xor of the selected numbers is greater than 0. Note: There is a minimum of 2 rows. Examples: Input: a[][] = {{7, 7, 7}, {10, 10, 7}} Output: Yes Input: a[][] = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {1, 1, 1}} Output: No Appr
6 min read
Find array such that no subarray has xor zero or Y
Given two integers X (1 ? X ? 15) and Y. The task is to find an array of the maximum possible length N such that all the elements in the array lie in between 1 and 2X and there exists no subarray such that xor value of the subarray is either 0 or Y. If there exist multiple answers then print any one of them. If no such array exists then print -1Exa
6 min read
Javascript Program for Number of unique triplets whose XOR is zero
Given N numbers with no duplicates, count the number of unique triplets (ai, aj, ak) such that their XOR is 0. A triplet is said to be unique if all of the three numbers in the triplet are unique. Examples: Input : a[] = {1, 3, 5, 10, 14, 15}; Output : 2 Explanation : {1, 14, 15} and {5, 10, 15} are the unique triplets whose XOR is 0. {1, 14, 15} a
3 min read
Minimum operations to make XOR of array zero
We are given an array of n elements. The task is to make XOR of whole array 0. We can do the following to achieve this. We can select any one of the elements.After selecting an element, we can either increment or decrement it by 1.We need to find the minimum number of increment/decrement operations required for the selected element to make the XOR
9 min read
Find Minimum Bitwise XOR By Removing Atmost One Element
Given an array A[] of length N. Then your task is to output the minimum possible bitwise XOR that can be obtained by removing at most one element. Examples: Input: N = 4, A[] = {2, 4, 3, 6}Output: 0Explanation: If we element 3 is removed from A[], then up updated A[] will be: {2, 4, 6}. Then cumulative bitwise XOR = (2^4^6) = 0. Which is minimum po
5 min read
Number of sub-sequences of non-zero length of a binary string divisible by 3
Given a binary string S of length N, the task is to find the number of sub-sequences of non-zero length which are divisible by 3. Leading zeros in the sub-sequences are allowed.Examples: Input: S = "1001" Output: 5 "11", "1001", "0", "0" and "00" are the only subsequences divisible by 3.Input: S = "1" Output: 0 Naive approach: Generate all the poss
5 min read
Practice Tags :