VOOZH about

URL: https://www.geeksforgeeks.org/dsa/xor-subarray-xors/

⇱ XOR of all subarray XORs - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

XOR of all subarray XORs

Last Updated : 24 Nov, 2025

Given an integer array arr[], consider every possible subarray and compute the bitwise XOR of its elements. Find the bitwise XOR of all these subarray XORs.

Examples :

Input: arr[] = [1, 2]
Output: 0
Explanation: All subarrays and their XORs:
XOR[1] = 1
XOR[2] = 2
XOR[1, 2] = 1 ^ 2 = 3
Final XOR: [1 ^ 2 ^ 3] = 0

Input: arr[] = [1, 2, 4]
Output: 5
Explanation: All subarrays and their XORs:
XOR[1] = 1
XOR[2] = 2
XOR[4] = 4
XOR[1, 2] = 1 ^ 2 = 3
XOR[2, 4] = 2 ^ 4 = 6
XOR[1, 2, 4] = 1 ^ 2 ^ 4 = 7
Final XOR: [1 ^ 2 ^ 4 ^ 3 ^ 6 ^ 7] = 5

[Naive Approach] Calculating XOR for Every Possible SubArray - O(n2) Time and O(1) Space

The idea is to consider every possible subarray of the array. For each subarray, we calculate the XOR of its elements. Finally, we XOR all these subarray results together to get the final answer.


Output
5

[Expected Approach] Using Subarray Contribution and XOR Property - O(n) Time and O(1) Space

Each element arr[i] (0-based index) appears in all subarrays that start at or before index i and end at or after index i. There are (i + 1) choices for the starting index (from 0 to i) and (n - i) choices for the ending index (from i to n-1), so the total number of subarrays containing arr[i] is (i + 1) * (n - i).

In the XOR of all subarrays, an element only contributes if it appears an odd number of times, because XORing a number an even number of times cancels it out. Therefore, we include arr[i] in the final XOR only if both (i + 1) and (n - i) are odd, which ensures the total count is odd.


Output
5


Comment