Problem Description
Given an integer array arr, count the number of triplets (i, j, k) that satisfy 0 <= i < j <= k < arr.length and where the XOR of the subarray from arr[i] to arr[j-1] is equal to the XOR of the subarray from arr[j] to arr[k]. In other words, letting a = arr[i] ^ ... ^ arr[j-1] and b = arr[j] ^ ... ^ arr[k], count the number of triplets where a == b.
Key Insights
- Using the properties of XOR, note that if a ^ b = 0 then a equals b.
- Define a prefix XOR array such that prefix[k] = arr[0] XOR arr[1] XOR ... XOR arr[k-1].
- The condition a == b is equivalent to prefix[i] == prefix[k+1], where i < k+1.
- For any such pair (i, k+1) with equal prefix XOR, any index j with i < j <= k is valid; hence contribution to count is (k - i).
- An O(n^2) solution is feasible given the constraint that the length of arr is at most 300.
Space and Time Complexity
Time Complexity: O(n^2) Space Complexity: O(n) for storing the prefix XOR array
Solution
We use a prefix XOR array to efficiently compute the XOR for any subarray. The key observation is that if we denote prefix[i] as the XOR of all elements before index i, then the XOR of the subarray from i to k is given by prefix[i] XOR prefix[k+1]. For the XOR for subarrays to be equal (i.e., a == b), we require prefix[i] == prefix[k+1]. For each pair of indices (i, k) that satisfy this condition, every index j with i < j <= k gives a valid triplet, contributing (k - i) to our answer. We iterate with two nested loops over possible starting and ending indices and update our running total of valid triplets accordingly.