VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-number-of-subsets-having-a-particular-xor-value/

⇱ Count number of subsets having a particular XOR value - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count number of subsets having a particular XOR value

Last Updated : 13 Jun, 2026

Given an array of integers arr[] and an integer k, count the number of subsets whose XOR of all elements is equal to k.

Examples :

Input: arr[] = [6, 9, 4, 2], k = 6
Output: 2
Explanation: The subsets having XOR equal to 6 are {6} and {4, 2}.

Input: arr[] = [1, 2, 3, 4, 5], k = 4
Output: 4
Explanation: The subsets having XOR equal to 4 are {4}, {1, 5}, {1, 2, 3, 4}, and {2, 3, 5}.

[Naive Approach] Generate All Subsets - O(2^n) Time and O(n) Space

Generate all subsets considering two choices for every element, either include it in the current subset or exclude it. Recursively explore both possibilities while maintaining the XOR of the selected elements. Whenever all elements have been processed, check whether the current XOR is equal to k. If it is, count the subset.


Output
2

[Better Approach] Using Dynamic Programming (Tabulation)

Let dp[i][x] represent the number of subsets formed using the first i elements whose XOR value is x. For each element, we have two choices: exclude it and keep the XOR unchanged, or include it and update the XOR. By filling the table row by row, we can compute the answer without recursion.


Output
2

Time Complexity: O(n * max_xor) - There are n * max_xor states, and each state is computed once.
Auxiliary Space: O(n * max_xor) - A DP table of size n * max_xor is used.

[Expected Approach] Space Optimized Dynamic Programming

In the tabulation approach, dp[i][x] depends only on the previous row dp[i - 1][]. Therefore, instead of storing all n rows, we can keep only the counts for the previous state. For each element, create a new DP array representing the updated counts after considering that element. This reduces the space complexity from O(n * max_xor) to O(max_xor) while maintaining the same time complexity.


Output
2

Time Complexity: O(n * max_xor) - For each element, all possible XOR values are processed once.
Auxiliary Space: O(max_xor) - Only two arrays of size max_xor are used.


Comment