27. All Subsets XOR Sum
โ GFG solution to the All Subsets XOR Sum problem: calculate sum of XOR values across all subsets using optimal bitwise OR technique with mathematical insight. ๐
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
You are given an array arr[]. Your task is to find the sum of XOR of all elements for every possible subset of the array. Subsets with the same elements should be counted multiple times.
An array a is a subset of an array b if a can be obtained from b by deleting some (possibly zero) elements of b.
Note: The answer is guaranteed to fit within a 32-bit integer.
๐ Examples
Example 1
Input: arr[] = [7, 2]
Output: 14
Explanation: Subsets are: [[], [7], [2], [7, 2]]
Sum of all XOR's = 0 + 7 + 2 + (7 ^ 2) = 0 + 7 + 2 + 5 = 14.Example 2
Input: arr[] = [1, 2, 3]
Output: 12
Explanation: Subsets are: [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
Sum of all XOR's = 0 + 1 + 2 + 3 + (1 ^ 2) + (1 ^ 3) + (2 ^ 3) + (1 ^ 2 ^ 3) = 12.๐ Constraints
$1 \le \text{arr.size()} \le 30$
$1 \le \text{arr}[i] \le 10^3$
โ
My Approach
The optimal approach uses Bitwise OR with Mathematical Optimization to solve this problem in linear time:
Bitwise OR + Left Shift Technique
Mathematical Insight:
For any bit position, if it's set (1) in the OR of all array elements, it will contribute to the final sum.
Each bit that is set in any element appears in exactly 2^(n-1) subsets.
The XOR sum equals: (OR of all elements) ร 2^(n-1).
Algorithm Steps:
Compute the bitwise OR of all array elements.
This OR value represents all possible bits that can be set across any subset.
Left shift the OR result by (n-1) positions, equivalent to multiplying by 2^(n-1).
Return the computed result.
Why This Works:
XOR has the property that each set bit in the OR contributes independently.
Every element participates in exactly half of all 2^n subsets.
The mathematical formula simplifies brute force O(n ร 2^n) to O(n).
๐ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. We perform a single pass through the array to compute the bitwise OR of all elements, which takes linear time.
Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for variables to store the OR result and perform the shift operation.
๐งโ๐ป Code (C++)
โ Code (Java)
๐ Code (Python)
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Let's make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated