885680. Sum of XOR of all possible subsets

Medium

Here is the detailed Markdown blog post for the GeeksforGeeks problem:

Sum of XOR of all possible subsets

Summary

Given an array of integers, find the sum of XOR (bitwise exclusive OR) of all possible subsets.

The key concepts involved in this problem are bit magic and data structures. We'll be using bitwise operations to calculate the XOR of each subset and then summing up these values.

Detailed Explanation

To solve this problem, we can use a greedy approach by iterating over all bits (0 to n-1) and calculating the XOR for each subset based on the bits. The idea is to maintain two variables: xorSum which stores the XOR of all subsets ending at the current bit position, and currXor which stores the XOR of the current subset.

Here's a step-by-step breakdown of the solution:

  1. Initialize xorSum to 0.
  2. Iterate over each bit (0 to n-1) in the array:
    • For each bit, calculate currXor as the XOR of all elements at that bit position whose value is different from the current bit.
    • Add currXor to xorSum.
  3. Return xorSum.

Here's an ASCII art diagram illustrating the process:

+-------+
| 0 1 1 |
+-------+
| XOR 1 |
| (0+1) |
+-------+
| XOR 2 |
| (0+1+1) |
+-------+

Time complexity: O(n), where n is the number of elements in the array. Space complexity: O(1), as we only use a constant amount of space.

Optimized Solutions

Java

View on GeeksforGeeks
public int sumOfXOR(int[] arr) {
    int xorSum = 0;
    for (int i = 0; i < (1 << arr.length); i++) {
        int currXor = 0;
        for (int j = 0; j < arr.length; j++) {
            if (((i >> j) & 1) != (arr[j] & 1)) {
                currXor ^= arr[j];
            }
        }
        xorSum ^= currXor;
    }
    return xorSum;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.