25. Game of XOR
β GFG solution to the Game of XOR problem: compute the bitwise XOR of all subarray XORs using mathematical contribution analysis and parity optimization. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given an integer array arr[]. The value of a subarray is defined as the bitwise XOR of all elements in that subarray.
Your task is to compute the bitwise XOR of the values of all possible subarrays of arr[].
π Examples
Example 1
Input: arr[] = [1, 2, 3]
Output: 2
Explanation:
xor[1] = 1
xor[1, 2] = 3
xor[2, 3] = 1
xor[1, 2, 3] = 0
xor[2] = 2
xor[3] = 3
Result: 1 ^ 3 ^ 1 ^ 0 ^ 2 ^ 3 = 2Example 2
π Constraints
$1 \le \text{arr.size()} \le 10^5$
$0 \le \text{arr}[i] \le 10^9$
β
My Approach
The optimal approach uses mathematical contribution analysis with parity checking to avoid the brute force generation of all subarrays:
Mathematical Contribution with Parity Optimization
Key Observation:
Each element
arr[i]appears in multiple subarrays.The element at index
iappears in exactly(i + 1) * (n - i)subarrays.Due to XOR properties, an element only contributes to the final result if it appears an odd number of times.
Parity Analysis:
Since
a ^ a = 0, if an element appears an even number of times, it cancels itself out.We only need to XOR elements that appear an odd number of times across all subarrays.
Efficient Calculation:
For each element at index
i, calculate its contribution count:(i + 1) * (n - i).Check if this count is odd using bitwise AND:
((i + 1) * (n - i)) & 1.If odd, include the element in the final XOR result.
Single Pass Solution:
Iterate through the array once, checking the parity condition for each element.
Accumulate the XOR of elements with odd contribution counts.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the size of the array. We perform a single traversal through the array, and for each element, we execute constant-time operations (multiplication, bitwise AND, and XOR).
Expected Auxiliary Space Complexity: O(1), as we only use a fixed number of variables (
xor_sum,n,i) regardless of the input size. No additional data structures are required.
π§βπ» 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