Open In App

Count number of subsets having a particular XOR value

Last Updated : 13 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of n numbers and a number K, find the number of subsets of arr[] having XOR of elements as K
Examples : 

Input:   arr[]  = {6, 9, 4,2}, k = 6
Output: 2
The subsets are {4, 2} and {6}
Input: arr[] = {1, 2, 3, 4, 5}, k = 4
Output: 4
The subsets are {1, 5}, {4}, {1, 2, 3, 4}
and {2, 3, 5}

We strongly recommend that you click here and practice it, before moving on to the solution.

Brute Force approach O(2n): One naive approach is to generate all the 2n subsets and count all the subsets having XOR value K, but this approach will not be efficient for large values of n.

Meet in the Middle Approach O(2n/2): 

An optimization over the naïve approach. We split the arrays and then generate subsets, thereby reducing the time complexity significantly than Brute Force Solution

Let us go over how it works. 

arr[] = {6 , 9 , 4 , 2}

Let us split this array in two halves.

arr1[] = {6 , 9}

arr2[] = {4 , 2}

Generating all possible XOR for arr1                                                    Generating all possible XOR for arr2

                 6  -> 0110                                                                                                4 -> 0100

                9  -> 1001                                                                                                2 -> 0010

                6 ^ 9  -> 1111                                                                                         4 ^ 2 -> 0110

                0 -> 0000                                                                                                 0 -> 0000

K=6 (0110)

arr1[i] ^ unknown = K

unknown = K ^arr1[i]

So, find the count of this unknown from arr2. Use a frequency map.

Follow the steps below to implement the above idea:

1) First partition the array in half and then generate the subsets XOR for each partition and store the frequency.

2) Iterate on the XOR values of partition P1 and search for its corresponding XOR complement value in part2 P2. If XOR value K is to be achieved by the subset, and x is the XOR subset in part1 P1 with y frequency, then K ^ x is the XOR complement value in part2 P2. The total number of subsets will be P1[x]*P2[K^x].

3) Return the answer after the loop terminates.

C++




//Author - RainX (ABHIJIT ROY, NIT AGARTALA)
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to generate all subsets and their XOR values
void generate(vector<int>& arr, int curr, int n, unordered_map<int, int>& XOR, int xorSubset) {
    if (curr == n) {
        XOR[xorSubset]++; // Store XOR values in the map
        return;
    }
    generate(arr, curr + 1, n, XOR, xorSubset ^ arr[curr]); // Include current element in XOR
    generate(arr, curr + 1, n, XOR, xorSubset); // Exclude current element from XOR
}
 
// Function to count subsets with XOR equal to K
int subsetXOR(vector<int>& arr, int N, int K) {
    unordered_map<int, int> P1, P2; // Maps for first and second half subsets' XOR
 
    generate(arr, 0, N / 2, P1, 0); // Generate XOR for first half
    generate(arr, N / 2, N, P2, 0); // Generate XOR for second half
 
    int cnt = 0; // Counter for subsets with XOR equal to K
 
    for (auto x : P1) {
        int find = K ^ x.first; // Find corresponding value in second half
        cnt += (P2[find] * x.second); // Increment count with the product of occurrences
    }
 
    return cnt; // Return count of subsets with XOR equal to K
}
 
int main() {
    vector<int> arr = {1, 2, 3, 4, 5}; // Given array
    int k = 4; // XOR value to search for
    int N = 5; // Size of the array
 
    cout << "Count of subsets is " << subsetXOR(arr, N, k); // Output the count of subsets
 
    return 0;
}
 
// Code by RainX (Abhijit Roy, NIT AGARTALA)


Java




//Author: Amar Singh IIT BHU Varanasi
 
import java.util.*;
 
class Main {
    // Function to generate all subsets and their XOR values
    static void generate(List<Integer> arr, int curr, int n, Map<Integer, Integer> XOR, int xorSubset) {
        if (curr == n) {
            XOR.put(xorSubset, XOR.getOrDefault(xorSubset, 0) + 1); // Store XOR values in the map
            return;
        }
        generate(arr, curr + 1, n, XOR, xorSubset ^ arr.get(curr)); // Include current element in XOR
        generate(arr, curr + 1, n, XOR, xorSubset); // Exclude current element from XOR
    }
 
    // Function to count subsets with XOR equal to K
    static int subsetXOR(List<Integer> arr, int N, int K) {
        Map<Integer, Integer> P1 = new HashMap<>();
        Map<Integer, Integer> P2 = new HashMap<>();
        generate(arr, 0, N / 2, P1, 0); // Generate XOR for the first half
        generate(arr, N / 2, N, P2, 0); // Generate XOR for the second half
        int cnt = 0; // Counter for subsets with XOR equal to K
        for (int x : P1.keySet()) {
            int find = K ^ x; // Find corresponding value in the second half
            if (P2.containsKey(find)) {
                cnt += P2.get(find) * P1.get(x); // Increment count with the product of occurrences
            }
        }
        return cnt; // Return count of subsets with XOR equal to K
    }
 
    public static void main(String[] args) {
        List<Integer> arr = Arrays.asList(1, 2, 3, 4, 5); // Given array
        int K = 4; // XOR value to search for
        int N = arr.size(); // Size of the array
        System.out.println("Count of subsets is " + subsetXOR(arr, N, K)); // Output the count of subsets
    }
}
 
//Author: Amar Singh IIT BHU Varanasi


Python3




# Author: Amar Singh IIT BHU Varanasi
 
def generate(arr, curr, n, XOR, xorSubset):
    if curr == n:
        XOR[xorSubset] = XOR.get(xorSubset, 0) + 1  # Store XOR values in the map
        return
    generate(arr, curr + 1, n, XOR, xorSubset ^ arr[curr])  # Include current element in XOR
    generate(arr, curr + 1, n, XOR, xorSubset)  # Exclude current element from XOR
 
def subsetXOR(arr, K):
    N = len(arr)
    P1, P2 = {}, {}
 
    generate(arr, 0, N // 2, P1, 0# Generate XOR for the first half
    generate(arr, N // 2, N, P2, 0# Generate XOR for the second half
 
    cnt = 0  # Counter for subsets with XOR equal to K
 
    for x in P1:
        find = K ^ x  # Find corresponding value in the second half
        cnt += P2.get(find, 0) * P1[x]  # Increment count with the product of occurrences
 
    return cnt  # Return count of subsets with XOR equal to K
 
arr = [1, 2, 3, 4, 5# Given array
k = 4  # XOR value to search for
 
print("Count of subsets is", subsetXOR(arr, k))  # Output the count of subsets
 
# Author: Amar Singh IIT BHU Varanasi


C#




using System;
using System.Collections.Generic;
 
class Program
{
    // Function to generate all subsets and their XOR values
    static void Generate(List<int> arr, int curr, int n, Dictionary<int, int> XOR, int xorSubset)
    {
        if (curr == n)
        {
            if (XOR.ContainsKey(xorSubset))
                XOR[xorSubset]++;
            else
                XOR[xorSubset] = 1;
            return;
        }
        Generate(arr, curr + 1, n, XOR, xorSubset ^ arr[curr]); // Include current element in XOR
        Generate(arr, curr + 1, n, XOR, xorSubset); // Exclude current element from XOR
    }
 
    // Function to count subsets with XOR equal to K
    static int SubsetXOR(List<int> arr, int K)
    {
        int N = arr.Count;
        Dictionary<int, int> P1 = new Dictionary<int, int>();
        Dictionary<int, int> P2 = new Dictionary<int, int>();
 
        Generate(arr, 0, N / 2, P1, 0);  // Generate XOR for the first half
        Generate(arr, N / 2, N, P2, 0);  // Generate XOR for the second half
 
        int cnt = 0; // Counter for subsets with XOR equal to K
 
        foreach (var x in P1)
        {
            int find = K ^ x.Key; // Find corresponding value in the second half
            if (P2.ContainsKey(find))
                cnt += P2[find] * x.Value; // Increment count with the product of occurrences
        }
 
        return cnt; // Return count of subsets with XOR equal to K
    }
 
    static void Main()
    {
        List<int> arr = new List<int> { 1, 2, 3, 4, 5 }; // Given array
        int k = 4; // XOR value to search for
 
        Console.WriteLine("Count of subsets is " + SubsetXOR(arr, k)); // Output the count of subsets
    }
}


Javascript




function generate(arr, curr, n, XOR, xorSubset) {
    if (curr === n) {
        XOR[xorSubset] = (XOR[xorSubset] || 0) + 1; // Store XOR values in the map
        return;
    }
    generate(arr, curr + 1, n, XOR, xorSubset ^ arr[curr]); // Include current element in XOR
    generate(arr, curr + 1, n, XOR, xorSubset); // Exclude current element from XOR
}
 
function subsetXOR(arr, K) {
    const N = arr.length;
    const P1 = {};
    const P2 = {};
 
    generate(arr, 0, Math.floor(N / 2), P1, 0);  // Generate XOR for the first half
    generate(arr, Math.floor(N / 2), N, P2, 0);  // Generate XOR for the second half
 
    let cnt = 0; // Counter for subsets with XOR equal to K
 
    for (let x in P1) {
        x = parseInt(x);
        const find = K ^ x; // Find corresponding value in the second half
        if (P2[find] !== undefined) {
            cnt += P2[find] * P1[x]; // Increment count with the product of occurrences
        }
    }
 
    return cnt; // Return count of subsets with XOR equal to K
}
 
const arr = [1, 2, 3, 4, 5]; // Given array
const k = 4; // XOR value to search for
const N = 5; // Size of the array
 
console.log("Count of subsets is " + subsetXOR(arr, k)); // Output the count of subsets


Output

Count of subsets is 4







Time Complexity: O(2n/2): where n is the size of the array
Auxiliary Space: O(2n/2): where n is the size of the array, this space is used as auxiliary stack space for recursion

Dynamic Programming Approach O(n*m): 
We define a number m such that m = pow(2,(log2(max(arr))+1))­ – 1. This number is actually the maximum value any XOR subset will acquire. We get this number by counting bits in largest number. We create a 2D array dp[n+1][m+1], such that dp[i][j] equals to the number of subsets having XOR value j from subsets of arr[0…i-1].

We fill the dp array as following: 

  1. We initialize all values of dp[i][j] as 0.
  2. Set value of dp[0][0] = 1 since XOR of an empty set is 0.
  3. Iterate over all the values of arr[i] from left to right and for each arr[i], iterate over all the possible values of XOR i.e from 0 to m (both inclusive) and fill the dp array asfollowing: 
           for i = 1 to n: 
                 for j = 0 to m: 
                       dp[i][j] = dp[i­-1][j] + dp[i­-1][j^arr[i-1]] 
    This can be explained as, if there is a subset arr[0…i­-2] with XOR value j, then there also exists a subset arr[0…i-1] with XOR value j. also if there exists a subset arr[0….i-2] with XOR value j^arr[i] then clearly there exist a subset arr[0…i-1] with XOR value j, as j ^ arr[i-1] ^ arr[i-1] = j.
  4. Counting the number of subsets with XOR value k: Since dp[i][j] is the number of subsets having j as XOR value from the subsets of arr[0..i-1], then the number of subsets from set arr[0..n] having XOR value as K will be dp[n][K]

C++




// arr dynamic programming solution to finding the number
// of subsets having xor of their elements as k
#include <bits/stdc++.h>
using namespace std;
 
// Returns count of subsets of arr[] with XOR value equals
// to k.
int subsetXOR(int arr[], int n, int k)
{
    // Find maximum element in arr[]
    int max_ele = arr[0];
    for (int i = 1; i < n; i++)
        if (arr[i] > max_ele)
            max_ele = arr[i];
 
    // Maximum possible XOR value
    int m = (1 << (int)(log2(max_ele) + 1)) - 1;
    if (k > m)
        return 0;
    // The value of dp[i][j] is the number of subsets having
    // XOR of their elements as j from the set arr[0...i-1]
    int dp[n + 1][m + 1];
 
    // Initializing all the values of dp[i][j] as 0
    for (int i = 0; i <= n; i++)
        for (int j = 0; j <= m; j++)
            dp[i][j] = 0;
 
    // The xor of empty subset is 0
    dp[0][0] = 1;
 
    // Fill the dp table
    for (int i = 1; i <= n; i++)
        for (int j = 0; j <= m; j++)
            dp[i][j]
                = dp[i - 1][j] + dp[i - 1][j ^ arr[i - 1]];
 
    //  The answer is the number of subset from set
    //  arr[0..n-1] having XOR of elements as k
    return dp[n][k];
}
 
// Driver program to test above function
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int k = 4;
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "Count of subsets is " << subsetXOR(arr, n, k);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


C




// arr dynamic programming solution to finding the number
// of subsets having xor of their elements as k
#include <math.h>
#include <stdio.h>
 
// Returns count of subsets of arr[] with XOR value
// equals to k.
int subsetXOR(int arr[], int n, int k)
{
    // Find maximum element in arr[]
    int max_ele = arr[0];
    for (int i = 1; i < n; i++)
        if (arr[i] > max_ele)
            max_ele = arr[i];
 
    // Maximum possible XOR value
    int m = (1 << (int)(log2(max_ele) + 1)) - 1;
    if (k > m)
        return 0;
    // The value of dp[i][j] is the number of subsets having
    // XOR of their elements as j from the set arr[0...i-1]
    int dp[n + 1][m + 1];
 
    // Initializing all the values of dp[i][j] as 0
    for (int i = 0; i <= n; i++)
        for (int j = 0; j <= m; j++)
            dp[i][j] = 0;
 
    // The xor of empty subset is 0
    dp[0][0] = 1;
 
    // Fill the dp table
    for (int i = 1; i <= n; i++)
        for (int j = 0; j <= m; j++)
            dp[i][j]
                = dp[i - 1][j] + dp[i - 1][j ^ arr[i - 1]];
 
    //  The answer is the number of subset from set
    //  arr[0..n-1] having XOR of elements as k
    return dp[n][k];
}
 
// Driver program to test above function
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int k = 4;
    int n = sizeof(arr) / sizeof(arr[0]);
    printf("Count of subsets is %d", subsetXOR(arr, n, k));
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java dynamic programming solution to finding the number
// of subsets having xor of their elements as k
import java.util.*;
import java.io.*;
 
class GFG {
 
    // Returns count of subsets of arr[] with XOR value
    // equals to k.
    static int subsetXOR(int[] arr, int n, int k)
    {
 
        // Find maximum element in arr[]
        int max_ele = arr[0];
 
        for (int i = 1; i < n; i++)
            if (arr[i] > max_ele)
                max_ele = arr[i];
 
        // Maximum possible XOR value
        int m = (1 << (int)(Math.log(max_ele) / Math.log(2) + 1)) - 1;
        if (k > m)
            return 0;
 
        // The value of dp[i][j] is the number of subsets
        // having XOR of their elements as j from the set
        // arr[0...i-1]
        int[][] dp = new int[n + 1][m + 1];
 
        // Initializing all the values of dp[i][j] as 0
        for (int i = 0; i <= n; i++)
            for (int j = 0; j <= m; j++)
                dp[i][j] = 0;
 
        // The xor of empty subset is 0
        dp[0][0] = 1;
 
        // Fill the dp table
        for (int i = 1; i <= n; i++)
            for (int j = 0; j <= m; j++)
                dp[i][j] = dp[i - 1][j] + dp[i - 1][j ^ arr[i - 1]];
 
        // The answer is the number of subset from set
        // arr[0..n-1] having XOR of elements as k
        return dp[n][k];
    }
 
    // Driver code
    public static void main(String arg[])
    {
        int[] arr = { 1, 2, 3, 4, 5 };
        int k = 4;
        int n = arr.length;
 
        System.out.println("Count of subsets is " + subsetXOR(arr, n, k));
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Python 3 arr dynamic programming solution
# to finding the number of subsets having
# xor of their elements as k
import math
 
# Returns count of subsets of arr[] with
# XOR value equals to k.
def subsetXOR(arr, n, k):
     
    # Find maximum element in arr[]
    max_ele = arr[0]
    for i in range(1, n):
        if arr[i] > max_ele :
            max_ele = arr[i]
             
    # Maximum possible XOR value
    m = (1 << (int)(math.log2(max_ele) + 1)) - 1
    if( k > m  ):
       return 0
 
 
    # The value of dp[i][j] is the number
    # of subsets having XOR of their elements
    # as j from the set arr[0...i-1]
 
    # Initializing all the values
    # of dp[i][j] as 0
    dp = [[0 for i in range(m + 1)]
             for i in range(n + 1)]
     
    # The xor of empty subset is 0
    dp[0][0] = 1
 
    # Fill the dp table
    for i in range(1, n + 1):
        for j in range(m + 1):
            dp[i][j] = (dp[i - 1][j] +
                        dp[i - 1][j ^ arr[i - 1]])
 
    # The answer is the number of subset
    # from set arr[0..n-1] having XOR of
    # elements as k
    return dp[n][k]
 
# Driver Code
arr = [1, 2, 3, 4, 5]
k = 4
n = len(arr)
print("Count of subsets is",
       subsetXOR(arr, n, k))
 
# This code is contributed
# by sahishelangia


C#




// C# dynamic programming solution to finding the number
// of subsets having xor of their elements as k
using System;
 
class GFG
{
     
// Returns count of subsets of arr[] with
// XOR value equals to k.
static int subsetXOR(int []arr, int n, int k)
{
    // Find maximum element in arr[]
    int max_ele = arr[0];
    for (int i = 1; i < n; i++)
    if (arr[i] > max_ele)
        max_ele = arr[i];
 
    // Maximum possible XOR value
    int m = (1 << (int)(Math.Log(max_ele,2) + 1) ) - 1;
    if( k > m  ){
       return 0; 
    }
    // The value of dp[i][j] is the number of subsets having
    // XOR of their elements as j from the set arr[0...i-1]
    int [,]dp=new int[n+1,m+1];
 
    // Initializing all the values of dp[i][j] as 0
    for (int i = 0; i <= n; i++)
        for (int j = 0; j <= m; j++)
            dp[i, j] = 0;
 
    // The xor of empty subset is 0
    dp[0, 0] = 1;
 
    // Fill the dp table
    for (int i = 1; i <= n; i++)
        for (int j = 0; j <= m; j++)
            dp[i, j] = dp[i-1, j] + dp[i-1, j^arr[i-1]];
 
    // The answer is the number of subset from set
    // arr[0..n-1] having XOR of elements as k
    return dp[n, k];
}
 
    // Driver code
    static public void Main ()
    {
        int []arr = {1, 2, 3, 4, 5};
        int k = 4;
        int n = arr.Length;
        Console.WriteLine ("Count of subsets is " + subsetXOR(arr, n, k));
    }
}
 
// This code is contributed by jit_t.


Javascript




<script>
 
    // Javascript dynamic programming solution
    // to finding the number of subsets
    // having xor of their elements as k
       
    // Returns count of subsets of arr[] with
    // XOR value equals to k.
    function subsetXOR(arr, n, k)
    {
 
        // Find maximum element in arr[]
        let max_ele = arr[0];
 
        for(let i = 1; i < n; i++)
            if (arr[i] > max_ele)
                max_ele = arr[i];
 
        // Maximum possible XOR value
        let m = (1 << parseInt(Math.log(max_ele) /
        Math.log(2) + 1, 10) ) - 1;
        if (k > m)
        {
           return 0; 
        }
 
        // The value of dp[i][j] is the number
        // of subsets having XOR of their
        // elements as j from the set arr[0...i-1]
        let dp = new Array(n + 1);
 
        // Initializing all the values of dp[i][j] as 0
        for(let i = 0; i <= n; i++)
        {
            dp[i] = new Array(m + 1);
            for(let j = 0; j <= m; j++)
            {
                dp[i][j] = 0;
            }
        }
 
        // The xor of empty subset is 0
        dp[0][0] = 1;
 
        // Fill the dp table
        for(let i = 1; i <= n; i++)
            for(let j = 0; j <= m; j++)
                dp[i][j] = dp[i - 1][j] +
                dp[i - 1][j ^ arr[i - 1]];
 
        // The answer is the number of
        // subset from set arr[0..n-1]
        // having XOR of elements as k
        return dp[n][k];
    }
     
    let arr = [ 1, 2, 3, 4, 5 ];
    let k = 4;
    let n = arr.length;
      
    document.write("Count of subsets is " + subsetXOR(arr, n, k));
     
</script>


PHP




<?php
// PHP arr dynamic programming
// solution to finding the number
// of subsets having xor of their
// elements as k
 
// Returns count of subsets of
// arr[] with XOR value equals to k.
function subsetXOR($arr, $n, $k)
{
    // Find maximum element in arr[]
    $max_ele = $arr[0];
    for ($i = 1; $i < $n; $i++)
    if ($arr[$i] > $max_ele)
        $max_ele = $arr[$i];
 
    // Maximum possible XOR value
    $m = (1 << (int)(log($max_ele,
                    2) + 1) ) - 1;
    if( $k > $m  ){
       return 0;
    }
    // The value of dp[i][j] is the
    // number of subsets having
    // XOR of their elements as j
    // from the set arr[0...i-1]
     
    // Initializing all the
    // values of dp[i][j] as 0
    for ($i = 0; $i <= $n; $i++)
        for ($j = 0; $j <= $m; $j++)
            $dp[$i][$j] = 0;
 
    // The xor of empty subset is 0
    $dp[0][0] = 1;
 
    // Fill the dp table
    for ($i = 1; $i <= $n; $i++)
        for ( $j = 0; $j <= $m; $j++)
            $dp[$i][$j] = $dp[$i - 1][$j] +
                          $dp[$i - 1][$j ^
                          $arr[$i - 1]];
 
    // The answer is the number
    // of subset from set arr[0..n-1]
    // having XOR of elements as k
    return $dp[$n][$k];
}
 
// Driver Code
$arr = array (1, 2, 3, 4, 5);
$k = 4;
$n = sizeof($arr);
echo "Count of subsets is " ,
     subsetXOR($arr, $n, $k);
 
// This code is contributed by ajit
?>


Output

Count of subsets is 4







Time Complexity: O(n * m)
Auxiliary Space: O(n * m)

Efficient approach : Space optimization

In previous approach the current value dp[i][j] is only depend upon the current and previous row values of DP. So to optimize the space complexity we use a single 1D array to store the computations.

Implementation steps:

  • Create a 1D vector dp of size m+1.
  • Set a base case by initializing the values of DP .
  • Now iterate over subproblems by the help of nested loop and get the current value from previous computations.
  • Now Create a temporary vector temp used to store the current values from previous computations.
  • At last return and print the final answer stored in dp[k].

Implementation: 
 

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to count the number of subsets with XOR equal to k
int subsetXOR(int arr[], int n, int k)
{
    // Find the maximum element in the array
    int max_ele = arr[0];
    for (int i = 1; i < n; i++)
        if (arr[i] > max_ele)
            max_ele = arr[i];
 
    // Calculate the maximum possible XOR value
    int m = (1 << (int)(log2(max_ele) + 1)) - 1;
 
    // If k is greater than the maximum possible XOR value, return 0
    if (k > m)
        return 0;
 
    // Create a vector to store the count of subsets with XOR equal to each possible value
    vector<int> dp(m + 1);
    dp[0] = 1; // There is one subset with XOR equal to 0 (empty subset)
 
    // Iterate over the array elements
    for (int i = 1; i <= n; i++)
    {
        // Create a temporary vector to store the previous row values
        vector<int> temp = dp;
 
        // Update the dp vector based on the previous row values
        for (int j = 0; j <= m; j++)
        {
            // Calculate the count of subsets with XOR equal to j using the previous row values
            dp[j] = temp[j] + temp[j ^ arr[i - 1]];
        }
    }
 
    // Return the count of subsets with XOR equal to k
    return dp[k];
}
 
int main()
{
    int arr[] = {1, 2, 3, 4, 5};
    int k = 4;
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Call the subsetXOR function and print the result
    cout << "Count of subsets is " << subsetXOR(arr, n, k);
 
    return 0;
}


Java




import java.util.Arrays;
 
public class SubsetXOR {
    // Function to count the number of subsets with XOR equal to k
    public static int subsetXOR(int[] arr, int n, int k) {
        // Find the maximum element in the array
        int maxEle = arr[0];
        for (int i = 1; i < n; i++) {
            if (arr[i] > maxEle) {
                maxEle = arr[i];
            }
        }
 
        // Calculate the maximum possible XOR value
        int m = (1 << (int) (Math.log(maxEle) / Math.log(2) + 1)) - 1;
 
        // If k is greater than the maximum possible XOR value, return 0
        if (k > m) {
            return 0;
        }
 
        // Create an array to store the count of subsets with XOR equal to each possible value
        int[] dp = new int[m + 1];
        dp[0] = 1; // There is one subset with XOR equal to 0 (empty subset)
 
        // Iterate over the array elements
        for (int i = 0; i < n; i++) {
            // Create a temporary array to store the previous row values
            int[] temp = Arrays.copyOf(dp, dp.length);
 
            // Update the dp array based on the previous row values
            for (int j = 0; j <= m; j++) {
                // Calculate the count of subsets with XOR equal to j using the previous row values
                dp[j] = temp[j] + temp[j ^ arr[i]];
            }
        }
 
        // Return the count of subsets with XOR equal to k
        return dp[k];
    }
 
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int k = 4;
        int n = arr.length;
 
        // Call the subsetXOR function and print the result
        System.out.println("Count of subsets is " + subsetXOR(arr, n, k));
    }
}


Python3




# Function to count the number of subsets with XOR equal to k
def subsetXOR(arr, k):
    n = len(arr)
 
    # Find the maximum element in the array
    max_ele = max(arr)
 
    # Calculate the maximum possible XOR value
    m = (1 << (int(max_ele).bit_length())) - 1
 
    # If k is greater than the maximum possible XOR value, return 0
    if k > m:
        return 0
 
    # Create a list to store the count of subsets with XOR equal to each possible value
    dp = [0] * (m + 1)
    dp[0] = 1  # There is one subset with XOR equal to 0 (empty subset)
 
    # Iterate over the array elements
    for i in range(1, n + 1):
        # Create a temporary list to store the previous row values
        temp = dp[:]
 
        # Update the dp list based on the previous row values
        for j in range(m + 1):
            # Calculate the count of subsets with XOR equal to j using the previous row values
            dp[j] = temp[j] + temp[j ^ arr[i - 1]]
 
    # Return the count of subsets with XOR equal to k
    return dp[k]
 
if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5]
    k = 4
 
    # Call the subsetXOR function and print the result
    print("Count of subsets is", subsetXOR(arr, k))


C#




using System;
using System.Linq;
using System.Collections.Generic;
 
class SubsetXORProgram {
    // Function to count the number of subsets with XOR
    // equal to k
    static int SubsetXOR(int[] arr, int n, int k)
    {
        // Find the maximum element in the array
        int maxEle = arr.Max();
 
        // Calculate the maximum possible XOR value
        int m = (1 << (int)(Math.Ceiling(
                     Math.Log(maxEle + 1, 2))))
                - 1;
 
        // If k is greater than the maximum possible XOR
        // value, return 0
        if (k > m)
            return 0;
 
        // Create a list to store the count of subsets with
        // XOR equal to each possible value
        List<int> dp = new List<int>(new int[m + 1]);
        dp[0] = 1; // There is one subset with XOR equal to
                   // 0 (empty subset)
 
        // Iterate over the array elements
        for (int i = 1; i <= n; i++) {
            // Create a temporary list to store the previous
            // row values
            List<int> temp = new List<int>(dp);
 
            // Update the dp list based on the previous row
            // values
            for (int j = 0; j <= m; j++) {
                // Calculate the count of subsets with XOR
                // equal to j using the previous row values
                dp[j] = temp[j] + temp[j ^ arr[i - 1]];
            }
        }
 
        // Return the count of subsets with XOR equal to k
        return dp[k];
    }
 
    static void Main()
    {
        int[] arr = { 1, 2, 3, 4, 5 };
        int k = 4;
        int n = arr.Length;
 
        // Call the SubsetXOR function and print the result
        Console.WriteLine("Count of subsets is "
                          + SubsetXOR(arr, n, k));
    }
}


Javascript




// Function to count the number of subsets with XOR equal to k
function subsetXOR(arr, n, k) {
    // Find the maximum element in the array
    let maxEle = arr[0];
    for (let i = 1; i < n; i++) {
        if (arr[i] > maxEle) {
            maxEle = arr[i];
        }
    }
 
    // Calculate the maximum possible XOR value
    let m = (1 << (Math.log2(maxEle) + 1)) - 1;
 
    // If k is greater than the maximum possible XOR value, return 0
    if (k > m) {
        return 0;
    }
 
    // Create an array to store the count of subsets with XOR equal to each possible value
    let dp = new Array(m + 1).fill(0);
    dp[0] = 1; // There is one subset with XOR equal to 0 (empty subset)
 
    // Iterate over the array elements
    for (let i = 0; i < n; i++) {
        // Create a temporary array to store the previous row values
        let temp = [...dp];
 
        // Update the dp array based on the previous row values
        for (let j = 0; j <= m; j++) {
            // Calculate the count of subsets with XOR equal to j using the previous row values
            dp[j] = temp[j] + temp[j ^ arr[i]];
        }
    }
 
    // Return the count of subsets with XOR equal to k
    return dp[k];
}
 
// Main function
function main() {
    let arr = [1, 2, 3, 4, 5];
    let k = 4;
    let n = arr.length;
 
    // Call the subsetXOR function and print the result
    console.log("Count of subsets is " + subsetXOR(arr, n, k));
}
 
// Call the main function
main();


Output

Count of subsets is 4

Time Complexity: O(n * m)
Auxiliary Space: O(m)

This article is contributed by Pranay Pandey.
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads