Count Triplets That Can Form Two Arrays of Equal XOR Problem
Description
LeetCode Problem 1442.
Given an array of integers arr.
We want to select three indices i, j and k where (0 <= i < j <= k < arr.length).
Let's define a and b as follows:
a = arr[i] ^ arr[i + 1] ^ ... ^ arr[j - 1]b = arr[j] ^ arr[j + 1] ^ ... ^ arr[k]
Note that ^ denotes the bitwise-xor operation.
Return the number of triplets (i, j and k) Where a == b.
Example 1:
Input: arr = [2,3,1,6,7]
Output: 4
Explanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)
Example 2:
Input: arr = [1,1,1,1,1]
Output: 10
Constraints:
1 <= arr.length <= 3001 <= arr[i] <= 10^8
Solution
Approach: XOR of the Whole Range
The key fact about XOR is that a == b exactly when a ^ b == 0. Here a ^ b is the XOR of the whole range arr[i..k], because a covers arr[i..j-1] and b covers arr[j..k], and together they cover i..k with no overlap.
So the split point j does not matter at all. If the range arr[i..k] XORs to 0, then every j with i < j <= k gives a valid triplet, which is k - i triplets. If it does not XOR to 0, no j works.
That turns the problem into: for every pair i <= k, check whether arr[i..k] XORs to 0, and if so add k - i. Fix i, then extend k to the right while keeping a running XOR s, so each range costs O(1).
When k == i the range is a single number, which is at least 1, so it never XORs to 0; and even if it did, it would add k - i = 0. That is why the loop can safely start at k = i.
Complexity: O(n2) time and O(1) extra space.
class Solution:
def countTriplets(self, arr: List[int]) -> int:
ans, n = 0, len(arr)
for i in range(n):
s = 0 # XOR of arr[i..k]
for k in range(i, n):
s ^= arr[k]
if s == 0:
# a == b exactly when arr[i..k] XORs to 0, and then any j in (i, k] works.
ans += k - i
return ans